I understand the case when a function may have less arguments than the function signature allows, such as:
function sum(x, y=1) { return x y; }
console.log(sum(5));
Or more parameters if its a vargs/rest function:
function sum(...rest) {
let s = 0;
for (let n of rest) s = n;
return s;
}
console.log(sum(1,2,3,4,5));
But why does the following not raise an error?
'use strict';
function addEmUp() {
let sum = 0;
for (let arg of arguments) sum = arg;
return sum;
}
console.log(addEmUp(1,2,3,4,5));
CodePudding user response:
The default values for parameters and the rest parameters are a relatively new functionality of JavaScript, they were introduced in ES2015. Before that, the only way to have a function with any number of arguments was by using the arguments
object. It has been available since the first versions of JavaScript.
No matter how a function accesses its actual parameters, it can be called with less or more parameters than its declaration requires. When there are less actual values than declared parameters on the call, the remaining parameters are not initialized (their value is undefined
), when the function is called with more values than it is declared, the extra values can be accessed only by using the arguments
object (or with the rest syntax).