Javascript post and pre-increment operator

post increment evaluates to un-incremented value of operand while pre increment evaluates to incremented value of operand.

Consider the following code block in javascript.

x = { a: 1 }
y = { b: x.a++ }
console.log(y) 
// { b: 1 }

z = { b: ++x.a }
console.log(z) 
// { b: 3 }

If you are like me, you are probably thinking shouldn’t it have printed 2 in both the cases?

The behaviour of ++ operator depends on its position with respect to the operand. If it is before the operand, it is known as pre-increment operator and if it is after the operand, it is known as post-increment operator.

The post increment operator will increment the operand but will evaluate to operand and not to the increment value.

x = 5
console.log(x++)
// 5
console.log(x)
// 6

The pre increment operator will increment the operand and will evaluate to incremented value.

x = 5
console.log(++x)
// 6
console.log(x)
// 6

Let’s this understanding, what do you think will be the output of following?

x = 5
y = x++ + ++x
console.log(y)
  • The expression is evaluated from left to right

  • First x++ will be evaluated, it will increment the x but the it will evaluate to current value of x i.e. 5.

  • Then ++x will be evaluated, at this point the value of x is 6, and ++x will increment it to 7.

  • So the value of y will be 12.

Reply

or to participate.