0
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)?

1
  • 3
    JavaScript doesn't have named parameters, you're positionally passing the result of an assignment expression. Commented Feb 1, 2024 at 17:29

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.