- Monte's snippets
- Posts
- Javascript post and pre-increment operator
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)
// 6The pre increment operator will increment the operand and will evaluate to incremented value.
x = 5
console.log(++x)
// 6
console.log(x)
// 6Let’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 thexbut the it will evaluate to current value ofxi.e.5.Then
++xwill be evaluated, at this point the value ofxis6, and++xwill increment it to7.So the value of
ywill be12.
Reply