Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is increment (++) operator in JavaScript?
The increment operator (++) increases a numeric value by one. It comes in two forms: pre-increment (++variable) and post-increment (variable++), which behave differently in expressions.
Syntax
++variable // Pre-increment: increment first, then return value variable++ // Post-increment: return value first, then increment
Pre-increment vs Post-increment
<html>
<body>
<script>
let a = 5;
let b = 5;
document.write("Pre-increment (++a): " + ++a + "<br>");
document.write("Value of a after: " + a + "<br><br>");
document.write("Post-increment (b++): " + b++ + "<br>");
document.write("Value of b after: " + b);
</script>
</body>
</html>
Pre-increment (++a): 6 Value of a after: 6 Post-increment (b++): 5 Value of b after: 6
Key Difference in Expressions
<html>
<body>
<script>
let x = 10;
let y = 10;
let result1 = x + ++x; // Pre-increment
document.write("x + ++x = " + result1 + "<br>");
let result2 = y + y++; // Post-increment
document.write("y + y++ = " + result2);
</script>
</body>
</html>
x + ++x = 21 y + y++ = 20
Comparison
| Operator | When increment happens | Value returned |
|---|---|---|
++variable |
Before use | New value |
variable++ |
After use | Original value |
Conclusion
Use pre-increment (++) when you need the incremented value immediately, and post-increment (++) when you need the original value first. Both forms increase the variable by one.
Advertisements
