Hafed
Hafed

Reputation: 35

how does Increment and Decrement work in 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;
};

Upvotes: 3

Views: 136

Answers (4)

VLAZ
VLAZ

Reputation: 29087

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.

Upvotes: 5

Temo Tchanukvadze
Temo Tchanukvadze

Reputation: 1522

Let's say n = 10
1. n++ will return the original value that n held before being incremented. And before going to the next operation n will be 11.
2. --n will decrease increased value(11) by 1, and then return the decreased value.
3. Finally, 10 - 10 is 0

Arithmetic Operations

Upvotes: 1

TopW3
TopW3

Reputation: 1527

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

Upvotes: 2

tano
tano

Reputation: 2817

This is a left to right evaluation and the incrementation is done after its value is used. So lets assume the input is 10 Evaluate to 10 then increase then decrease so 10 - 10 the final expression.

Upvotes: 1

Related Questions