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

Unexpected output when using default parameters in JavaScript function

function add(x=1, y=2){
    return x + y;
}
console.log(add(y=4));

Output I am getting is 6, Why? How does this work?

I was expecting 5 as y=4 and x will retain its default value.

Is there any other method of doing this without using add(undefined, 4)?

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

>Solution :

The expression y=4 sets the (global, in this case) variable y to 4 and returns its value, so what you are doing is equivalent to this:

y = 4
console.log(add(4))

So, the first argument is now 4 and the second is the default 2, resulting in a sum of 6, and as side-effect you created a useless global variable (or clobbered a local one).

The correct way is, as you noticed, add(undefined, 4).

If you’d like to "name" your arguments, you could use a single object as argument:

function add ({ x = 1, y = 2 } = {}) {
    return x + y
}

console.log(add({ y: 4 })) // 5

This works thanks to destructuring. (The = {} allows to use add() without any argument whatsoever – without it, you’d have to write add({}).)

Note that then you need to always specify the names.

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