What is the difference between a++ and ++a in JavaScript?

In JavaScript, ++a (pre-increment) and a++ (post-increment) both increase a variable by 1, but they differ in when the increment happens and what value they return.

Pre-increment (++a)

++a increments the variable first, then returns the new value. The ++ operator comes before the operand.

Post-increment (a++)

a++ returns the current value first, then increments the variable. The ++ operator comes after the operand.

Example: Basic Difference

<html>
   <body>  
      <script>
          let a = 10;
          let b = 10;
          
          // Pre-increment: increment first, then return
          let preResult = ++a;
          document.write("a after ++a: " + a + "<br>");
          document.write("Value returned by ++a: " + preResult + "<br><br>");
          
          // Post-increment: return first, then increment
          let postResult = b++;
          document.write("b after b++: " + b + "<br>");
          document.write("Value returned by b++: " + postResult);
      </script>
   </body>
</html>
a after ++a: 11
Value returned by ++a: 11

b after b++: 11
Value returned by b++: 10

Example: In Expressions

<html>
   <body>  
      <script>
          let x = 5;
          let y = 5;
          
          let result1 = x + ++x;  // x becomes 6, then 6 + 6
          document.write("x + ++x = " + result1 + " (x is now " + x + ")<br>");
          
          let result2 = y + y++;  // 5 + 5, then y becomes 6
          document.write("y + y++ = " + result2 + " (y is now " + y + ")");
      </script>
   </body>
</html>
x + ++x = 12 (x is now 6)
y + y++ = 10 (y is now 6)

Comparison

Operation When Increment Happens Value Returned Use Case
++a Before returning New value Need incremented value immediately
a++ After returning Original value Need original value, increment later

Common Use in Loops

<html>
   <body>  
      <script>
          // Both work the same in for loops
          document.write("Using i++: ");
          for (let i = 0; i < 3; i++) {
              document.write(i + " ");
          }
          
          document.write("<br>Using ++i: ");
          for (let i = 0; i < 3; ++i) {
              document.write(i + " ");
          }
      </script>
   </body>
</html>
Using i++: 0 1 2 
Using ++i: 0 1 2 

Conclusion

The key difference is timing: ++a increments then returns the new value, while a++ returns the original value then increments. Both end up incrementing the variable by 1.

Updated on: 2026-03-15T21:48:28+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements