Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!