I found this ES6 code in a book:
let value = 5;
function getValue() {
return value++;
}
function add(first, second = getValue()) {
return first + second;
}
console.log(add(1, 1)); // 2
console.log(add(1)); // 6
Why does running console.log(add(1));
return 6 as the value, which means it is taking the parameter second
as 5 although my code explicitly specifies that the getValue
function should return value++
- which means the first time it is run, the getValue
function should be returning 6 and add
should be returning 7. I am running this code in the Firefox console - am I missing something?
Default arguments are evaluated at call time, meaning the function getValue
invoked every time you invoke add
- not when the code is initially run. Since you're using postfix increment, getValue
will return 5 the first time you invoke add
, then 6, 7, etc. Postfix increment returns the previous value, then increments, for example:
var x = 5
var foo = x++;
Here, foo
is given the value 5, then x
is incremented. Thus, in your example, the getValue
function is actually returning 5 instead 6, then incrementing value
when you first invoke it. If you want 6, 7, 8, use prefix increment which returns the value after incrementing:
++x;
This will increment value
, then return that incremented value. You could even use compound addition:
x += 1;
This explicitly reassigns x
before you access it again. Further reading on those operators here.