Reputation: 4939
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?
Upvotes: 2
Views: 99
Reputation: 57982
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.
Upvotes: 1
Reputation: 739
Hi this is called 'Default value' for parameters. It's mean that you can set Default value for each parameters in function definition .
function add(first, second = getValue()) {
return first + second;
}
in this case 'second = getValue()', 'getValue()' is defulat value for 'second 'parameter.
when you do
console.log(add(1, 1)); // 2
because
first==>1
second==>1
console.log(add(1)); // 6
because first==>1 second==>getValue() ===> 6
Upvotes: -1
Reputation: 3346
I believe your problem is not related to ecmascript-6
, but in not understand the ++
operator correctly.
According to the documentation:
Unary operator. Adds one to its operand. If used as a prefix operator (++x), returns the value of its operand after adding one; if used as a postfix operator (x++), returns the value of its operand before adding one.
Replacing value++
with either ++value
or value + 1
should solve your issue.
Upvotes: 1
Reputation: 1146
Because you use the postfix expression, if you use prefix expression then you will get 7.
"If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing. If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing".
Upvotes: 1
Reputation: 477
value++
gets the value before increasing it,you should do either
++value
or
value+=1;
return value
Upvotes: 1