Arguments

You can call JavaScript functions with fewer or more arguments than the number they expect!

Fewer Arguments

Missing argument? Parameter is undefined:

function myfunction (x, y) {
  console.log(x, y);
}

myfunction(2);

This feature can be used to create optional parameters; check for undefined parameters and assign them a default value.

In modern JavaScript, you can use default parameter values by assigning a value to a parameter in the function signature.

function average(x, y = x) {
  return (x + y) / 2;
}

Multiple default arguments ok:

function average(x = 0, y = x) {
  return (x + y) / 2;
}

console.log(average(2,3));
console.log(average(2));
console.log(average());

More Arguments

If you provide a function with more arguments than it expects, it will ignore the extra ones!

function myfunction (x, y) {
  console.log(x, y);
}

myfunction(1, 2, 3, 4, 5, 6);

Rest Parameters/Spread Operator

We've seen the "rest parameters" in the destructuring assignment with arrays and objects. You can use the same pattern to capture a variable number of arguments:

function total(...args) {
  let sum = 0;
  for (x of args) sum += x;
  return sum;
}

console.log(total(1));
console.log(total(1, 2));
console.log(total(1, 2, 3));
console.log(total(1, 2, 3, 4));

JavaScript has a "spear operator" which looks identical to the "rest operator" but its purpose is to expand (spread out) the elements of an iterable object.

const numbers = [3, 4, 5]
const result = total(...numbers);

You can create a function that takes both named parameters and rest parameter but in that case the rest parameter must be the last parameter.

function myFunction (arg1, arg2, ...rest) { 
  /* do something awesome with all the arguments! */ 
}

Arguments Object

If you are puzzled by how functions can be called with fewer/more arguments, here is an explanation. It turns out, the named parameters of a function are more like guidelines than anything else. Every function has access to an array-like object called arguments. This object holds all of the values passed to the function.

function myfunction () {
  for (let i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}

myfunction(1, 2, 3, 4);

If you declare a function with \(n\) named parameters, JavaScript will assign the first \(n\) elements of arguments to those parameters, in order.

Caution: Arrow function do no have argumnets object.