Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Function Rest Parameter

The rest parameter (...) allows a function to treat an indefinite number of arguments as an array.

Example

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

let x = sum(491625291006677);

The Arguments Object

JavaScript functions have a built-in arguments object, which holds an array-like collection of the arguments passed to the function, enabling tasks like finding the highest value in a list of numbers.

Example

x = findMax(11235001154488);

function findMax() {
  let max = –Infinity;
  for (let i = 0; i < arguments.length; i++) {
    if (arguments[i] > max) {
      max = arguments[i];
    }
  }
  return max;
}

Or create a function to sum all the provided input values.

Example

x = sumAll(11235001154488);

function sumAll() {
  let sum = 0;
  for (let i = 0; i < arguments.length; i++) {
    sum += arguments[i];
  }
  return sum;
}

If a function is called with more arguments than declared, the extra arguments can be accessed through the arguments object.