DEV Community

Bassem
Bassem

Posted on

2 1

What's the value of x?

Hey, devs from all over the world. 😊

let x = 0;

x++;
x = x++;
x = ++x;

console.log(x);
Enter fullscreen mode Exit fullscreen mode

What's the value of x? πŸ€”πŸ€”

Top comments (4)

Collapse
 
gaberomualdo profile image
Gabe Romualdo β€’ β€’ Edited

Placed before a variable, "++" adds one to the variable and the expression with "++" equals the new value of the variable + 1. This can be seen in line 4, where "x = ++x;" really means "x = (x + 1)".

Placed after a variable, however, "++" adds one to the variable and the expression with "++" equals the first value of the variable, without 1 added. This is why line 3, "x = x++;" has no effect β€” because the "x = x + 1" execution that the "++" gives is executed but then replaced by the the previous value of x.

In the end, you have:

let x = 0; // x = 0

x++; // x = x + 1 --> x = 1
x = x++; // x = x --> x = 1
x = ++x; // x = x + 1 --> x = 2

console.log(x); // 2

I hope my explanation made sense to you, was a bit hard to explain.

β€” Gabriel

Collapse
 
thinkdigitalsoftware profile image

3?
Dangit. I believe it would be 3 in dart

Collapse
 
bassemibrahim profile image
Bassem β€’

Well, I am not sure about dart. But we can try it out!!
In javascript its 2 for sure.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay