ARGUMENTS, REST AND SPREAD

JS

Parameters passed to a function are also available through the arguments object, it is an array-like object with which it is possible to access the elements passed as input. The following code clarifies this topic.

Copy to Clipboard

THE PARAMETERS OF THE FUNCTIONS

A JavaScript function does not perform any checks on parameter values (arguments). Earlier in this tutorial,

you learned that functions can have parameters:

function functionName(parameter1, parameter2, parameter3) {
  // code to be executed
}

The function parameters are the names listed in the function definition. The arguments to the function are the real values passed (and received) by the function.

RULES OF PARAMETERS

The JavaScript function definitions do not specify data types for parameters. JavaScript functions do not perform type checking on passed arguments and do not check the number of arguments received.

DEFAULT PARAMETERS

If a function is called with missing arguments (fewer than declared), the missing values are set to undefined. Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter:

function myFunction(x, y) {
  if (y === undefined) {
    y = 2;
  }
}

ECMAScript 2015 allows default parameter values in the function declaration:

function myFunction(x, y = 2) {
  // function code
}

DEEPENING OF ARGUMENTS OBJECT

JavaScript functions have a built-in object called argument object. It contains an array of arguments used when the function was called (invoked). This way you can simply use a function to find (for example) the highest value in a list of numbers:

x = findMax(1, 123, 500, 115, 44, 88);

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

let’s see another example.

x = sumAll(1, 123, 500, 115, 44, 88);

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

If a function is called with too many arguments (more than declared), these arguments can be reached using the arguments object.

THE JAVASCRIPT LANGUAGE

THE JAVASCRIPT LANGUAGE

LINK TO THE CODE ON GITHUB

GITHUB