• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 274
  • Last Modified:

pre & post operands in javascript


I want to make sure I understand the different results between the three code examples included of pre & post increment operands.

Example A:
i = 1;
j = ++i;

Example B:
i = 1;
j = i++;

Example A sets both i and j to 2 whereas example B sets i to 2 and j to 1.  
I want to make sure why j equals 1 in example B: I believe it is because the increment operand is post which means this code:

j = i++;

Is read like this:

j equals i which equals 1 (j = i)
Increment i so it equals 2 (i++)

Am I correct in my reading of the code from example B?  If I am correct, then I would like to apply this logic to the following code:

Example C:
var i = 1;
var j = ++i;  // pre-increment:  j equals 2; i equals 2
var k = i++;  // post-increment: k equals 2; i equals 3

Based on the code above, does k equal 2 because i was previously incremented in var j above it and the new value of i (2) is carried over to the code: var k = i++?  
2 Solutions
You are correct.  ++i means increment i then use the result's value.  i++ means use i's value then increment i.
Anil GolamariCommented:
Yes you can use above code to get output as i =3, j= 2, k =2.
max7Author Commented:
Thanks to you both for the help!

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now