Can someone please explain why this function returns 0?
Shouldn't it return 1 since n++ = n and --n = n-1?
var x = function(n) {
return n++ - --n;
};
n++ is a post-increment, so first return the value, then will add 1 to it:
var n = 1;
console.log(n++); //shows 1, increments `n` to 2
console.log(n);//shows 2
console.log(n++); //shows 2, increments `n` to 3
--n is a pre-decrement - the value is first reduced by 1 and then return
var n = 3;
console.log(--n); //shows 2, `n` is already set to 2
console.log(n);//shows 2
console.log(--n); //shows 1, `n` is already set to 1
Here is an example to explain how this is being evaluated: When it's being evaluated:
var x = function (n) {
return n++ - --n;
};
x(5);
0. First n = 5 we go from there:
n = 5
n++ - --n
1. The post-increment has the highest precedence here, so we start with that.
2.n++ will return 5 but also change n to 6. So if we resolve that we have:
n = 6
5 - --n
3. Next in the order of precedence is the the pre-decrement operation.
4. --n will reduce n and return the new value, so:
n = 5
5 - 5
5. Finally, we solve the subtraction and get 0.
n++ - --n
if n = 10, then the value of (n++) is 10, but after that n is increased by one. So n = 11 after evaluating (n++). if n = 11, (--n) = 10.
n++ - --n
--- ----- ---
10 n = 11 10
so the result is 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With