Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does Increment and Decrement work in Javascript

Tags:

javascript

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;
};
like image 390
Hafed Avatar asked Dec 06 '25 05:12

Hafed


2 Answers

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.

like image 90
VLAZ Avatar answered Dec 08 '25 17:12

VLAZ


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

like image 32
TopW3 Avatar answered Dec 08 '25 17:12

TopW3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!