Parameters & Arguments

Default Parameters

Example

function makeTea(sugar = 1, milk = true) {
  return `Tea with ${sugar} sugar${milk ? " and milk" : ""}`;
}
console.log(makeTea());
console.log(makeTea(2, false));
console.log(makeTea(undefined, false));   // undefined uses the default

Output

Tea with 1 sugar and milk
Tea with 2 sugar
Tea with 1 sugar

Rest Parameters

Example

...name collects the remaining arguments into an array:

function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3));
console.log(sum(10, 20, 30, 40));

Output

6
100

Object Parameters

Example

With many options, pass one object and destructure it. Order no longer matters and calls are self-explanatory:

function createUser({ name, role = "student", active = true }) {
  return { name, role, active };
}
console.log(createUser({ name: "Neha", role: "mentor" }));

Output

{ name: 'Neha', role: 'mentor', active: true }