0
var x = 3;
var y = x++;

Can someone tell me why var y = 3 and x++ = 4.

I assumed x++ = 4 therefore y = 4 but it's not.

This dummy needs help understanding why y is not 4 but 3

Ele
  • 33,468
  • 7
  • 37
  • 75
Eian Lee
  • 3
  • 1
  • Java and JavaScript use the same syntax for variables increments. So Java explanation in that regard applies to JavaScript. – PM 77-1 Feb 24 '19 at 20:25
  • https://stackoverflow.com/questions/3469885/somevariable-vs-somevariable-in-javascript – PM 77-1 Feb 24 '19 at 20:27

3 Answers3

0

x++ => The ++ after the variable is the post-increment operator. It means that the variable uses the original value and then increments the value after an operation

var x=3;
var y=x++;
console.log(y)

Similarly there is a pre-increment operator that increments values first and then uses that value

var x=3;
var y=++x;
console.log(y)

Basically ++x: load x , increment, use. x++: load x , use, increment. This is the reason why x++ still gives 3. The values is first used then incremented.

ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

Because var y = x++; means assign value of x to y and then increment the value of x by 1.

similarly var y = ++x; will have opposite meaning ie. increment x first and then assign it to y.

so.

x = 3
var y = x++; //means y = 3, x = 4;

and

x = 3
var y = ++x; //means y = 4, x = 4;
Gaurav Saraswat
  • 1,353
  • 8
  • 11
0

Because the ++ is after x : javascript increment and decrement

When you use the increment/decrement operator after the operand, the value will be returned before the operand is increased/decreased.

To in crement the value before returning it, put the ++ before the variable name ++x :

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

console.log(x,y)

var a = 3;
var b = ++a;

console.log(a,b);
Taki
  • 17,320
  • 4
  • 26
  • 47