3

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);

3
  • Summary: 1. Convert its operand to a number. 2. Add 1 to the operand. 3. Assign the incremented value to the operand. Commented Jun 28, 2022 at 10:57
  • The first code block evaluates to myVar = 3 + 3 + 4; // 10, so we assign the result of adding all the operands (those being ++myVar, myVar++, and myVar--). The second one evaluates to 3 + 3 + 4, but that does nothing with the calculation, so all we see is the side effects of running ++ and -- on myVar, where it ends up as 3. Commented Jun 28, 2022 at 11:06
  • Thank you a lot for all of you for taking your time to provide an explanation here for my query Commented Jun 28, 2022 at 14:14

2 Answers 2

3

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 :)

Sign up to request clarification or add additional context in comments.

Comments

1

As @Teemu said. Reading the documentation is really helpful. Documentation

Maybe this helps also to understand this.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.