Reputation: 5178
So I'm wondering why
var x=5
function foo(){
return x++
}
foo()
returns 5 and
var x=5
function foo(){
return ++x
}
foo()
returns 6.
Is it because the precedence of the ++
operator excludes it from being executed before the return - ie. the precedence is (return x)++
? Or is there something tricky going on?
Upvotes: 1
Views: 5146
Reputation: 21130
It's pre/post increment. It's just how the operators work. ++var
is pre increment which means the value is incremented before returning and var++
is post increment, where the value is incremented after returning.
You can find more details about these semantics here.
Upvotes: 8