Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does increment operator work in javascript? directly assigns value to variable?

how does below code give result as 10

var myVar = 2;
myVar = ++myVar + myVar++ + myVar--;
console.log(myVar);

and when directly given as below without assigning to myVar give result as 3 in javascript?

var myVar = 2;
++myVar + myVar++ + myVar--;
console.log(myVar);
like image 376
apoorva Avatar asked Aug 04 '26 11:08

apoorva


1 Answers

There are two main factors we need to analyze:

Pre-Increment - The variable is first incremented, and then its value is used:

++x

Post-Increment - The variable value is first used, and then the value is incremented:

x++

With the first example:

var myVar = 2;
myVar = ++myVar + myVar++ + myVar--;
console.log(myVar);

The ++myVar increments the value from 2 to 3 first, so the value 3 is used. Then, for myVar++, the value 3 is used first, and then it is incremented to 4. For myVar--, the 4 is used, and then the value decrements from 4 to 3.

In the end, the expression will be: 3 + 3 + 4 = 10

For the second example:

var myVar = 2;
++myVar + myVar++ + myVar--;
console.log(myVar);

The individual +'s between the myVar are doing nothing. They are adding them together, but there is no variable storing that value. So the only thing that line does is apply the changes of ++myVar, myVar++, and myVar-- to myVar, giving it a value of 3 (from 2 to 3 to 4 to 3).

I hope this helped! Please let me know if you need any further clarification or details :)

like image 87
Aniketh Malyala Avatar answered Aug 05 '26 23:08

Aniketh Malyala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!