Function arguments, the arguments object, rest, and spread

suggest change

Functions can take inputs in form of variables that can be used and assigned inside their own scope. The following function takes two numeric values and returns their sum:

function addition (argument1, argument2){
    return argument1 + argument2; 
}

console.log(addition(2, 3)); // -> 5

arguments object

The arguments object lists the values that were passed. It does not include parameters filled by defaults. It exists even when the function declares no parameters. It is array-like, not an Array.

(function() { console.log(arguments); })(0, 'str', [2, 3]);

Although when printing arguments the output resembles an Array, it is in fact an object:

(function() { console.log(typeof arguments) })(); // -> object

Rest parameters: function (...parm) {}

A rest parameter collects the remaining arguments into a real Array. typeof an array is still "object". In the call below, b is [1, "2", [3], {i: 4}]. b[2] stringifies to "3", so the concatenation is "123". {i: 4} is b[3] and is not printed.

(function(a, ...b){console.log(typeof b+': '+b[0]+b[1]+b[2]) })(0,1,'2',[3],{i:4});
// -> object: 123

Spread parameters: function_name(...varb);

Spread in a call passes an iterable’s elements as separate arguments. It does not pass the array as one object. Math.max(...nums) is Math.max(2, 42, -1).

const nums = [2,42,-1];
console.log(...['a','b','c'], Math.max(...nums)); // -> a b c 42

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents