Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mismatched parameters

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

'use strict';
function addEmUp() {
    let sum = 0;
    for (let arg of arguments) sum += arg;
    return sum;
}
console.log(addEmUp(1,2,3,4,5));

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading