Function Arguments and Parameters

A function can accept input values. Those values are called arguments, and they are assigned to the parameters named in the function definition. In JavaScript, we can call a function with fewer or more arguments than it declares.

Optional Parameters

When we call a function and leave out an argument, the parameter that did not get a value is undefined. That is how we make a parameter optional.

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

displayValues(5);  // Output: 5 undefined

Default Parameters

We can give a parameter a default value right in the function signature. If the argument is left out, the parameter gets the default value instead of undefined.

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

You can also define multiple parameters with default values:

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

console.log(calculateAverage(3, 4));  // 3.5
console.log(calculateAverage(3));  // 3
console.log(calculateAverage());  // 0

Excess Arguments

We can also call a function with more arguments than it declares parameters. The extra arguments are ignored by the function body unless we capture them.

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

printValues(1, 2, 3, 4);  // Output: 1 2

Rest Parameters

If a function needs to take an arbitrary number of arguments, we can use a rest parameter. It gathers any number of trailing arguments into an array.

function sumAll(...numbers) {
  let sum = 0;
  for (const num of numbers) {
    sum += num;
  }
  return sum;
}

console.log(sumAll(1, 2, 3, 4));  // Output: 10

Spread Operator

The spread operator is closely related. It expands an iterable, such as an array, into individual values wherever multiple arguments or elements are expected.

const values = [7, 8, 9];
console.log(sumAll(...values));  // Output: 24

The arguments Object

Inside a function, we have access to a special array-like object called arguments. It contains all the values passed to the function. That gives us another way to handle a call with more or fewer arguments than the function declares.

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

showArguments(10, 20, 30, 40);  // 10 20 30 40