SeriousBurn
SeriousBurn

Reputation: 3

In an increment, why does the value of the variable get passed instead of the value as well as the increment?

Here's my code:

var x = 3;
var y = x++;
y += 1;

Output: y = 4

I know the computer is right, but I'm not sure why the computer is right. y gets assigned the value 3 from x, then it increments it to 4 in line 2. So, the output from line 3 should be 5, correct?

From what I've read, y gets assigned the value of x before the increment happens, but when it does happen, why does the value of y not change?

Upvotes: 0

Views: 6841

Answers (3)

Emeeus
Emeeus

Reputation: 5250

x++ return the value and then add 1. See this:

var x = 3;
var y = x++;// x return 3 and then add 1, y is 3 
y += 1;//3 + 1 = 4
console.log(y)
console.log(x)//x return 4 

Upvotes: 1

Adrian Pop
Adrian Pop

Reputation: 1967

There is a difference between pre-increment (++x) and post-increment (x++).

A pre-increment operator is used to increment the value of a variable before using it in a expression. In the pre-increment, value is first incremented and then used inside the expression. Let's say we have:

a = ++x;

Here, if the value of ‘x’ is 10 then value of ‘a’ will be 11 because the value of ‘x’ gets modified before using it in the expression. This is equivalent with:

x = x + 1;
a = x;

A post-increment operator is used to increment the value of variable after executing expression completely in which post increment is used. In the Post-Increment, value is first used in a expression and then incremented. Let's say we have:

a = x++;

Here, suppose the value of ‘x’ is 10 then value of variable ‘a’ will be 10 because old value of ‘x’ is used. This is equivalent with:

a = x;
x = x + 1;

You can read more on the interned about this (for example, here or here).

Cheers!

// Post-increment example
console.log("post-increment examples");
let x = 10;
a = x++;
console.log(x, a);

x = 10;
a = x;
x = x + 1;
console.log(x, a);

// Pre-increment example
console.log("pre-increment examples");
x = 10;
a = ++x;
console.log(x, a);

x = 10;
x = x + 1;
a = x;
console.log(x, a);

Upvotes: 3

rollingthedice
rollingthedice

Reputation: 1125

In your assignment y = x++; the value of y is first assigned to x and then the variable x gets incremented by 1. By performing this operation y becomes 3 and x is 4. Then after running y +=1 computer will calculate 3+1 = 4

If you're expecting y to be 5 you should do y = ++x;. By doing this x will first get incremented by 1 and then assigned to y so we will have y = 4 and x = 4 following the y += 1 (4+1=5)

Upvotes: 4

Related Questions