JavaScript – Increment (++)
JavaScript Increment (++) Arithmetic Operator is used to increment the given number by one.
Increment Operator Symbol
The symbol used for Increment Operator is ++
. There should be no space between the two +
symbols.
Syntax
The syntax to use Increment Operator with an operand is
operand++
++operand
The first notation operand++
is called post-increment, and the second notation ++operand
is called pre-increment.
Post-increment means, the value of the operand is incremented after the execution of current statement.
Pre-increment means, the value of the operand is incremented and then the current statement is executed.
In both the cases, the Increment operator modifies the original operand, and also returns the value.
Examples
In the following example, we take a numeric value and increment it by using using Increment (++) Operator.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var a = 4;
document.getElementById('output').innerHTML += 'Original Value : ' + a;
a++;
document.getElementById('output').innerHTML += '\nIncremented Value : ' + a;
</script>
</body>
</html>
In the following example, we try to show the difference between pre-increment and post-increment notations.
Post-Increment
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var a = 4;
document.getElementById('output').innerHTML += 'a : ' + a;
var result = a++;
document.getElementById('output').innerHTML += '\nAfter increment\na : ' + a;
document.getElementById('output').innerHTML += '\nresult : ' + result;
</script>
</body>
</html>
The value in result
is same as a
, because a
is incremented after the execution of this assignment statement let result = a++;
. Therefore, result
is assigned with the value of a
which is 4
, and for the next statement, the value of a
becomes 5
, hence post-increment.
Pre-Increment
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var a = 4;
document.getElementById('output').innerHTML += 'a : ' + a;
var result = ++a;
document.getElementById('output').innerHTML += '\nAfter increment\na : ' + a;
document.getElementById('output').innerHTML += '\nresult : ' + result;
</script>
</body>
</html>
Since, in pre-increment, a
is incremented first and then assigned to result
, the value in result
is 5
.
Conclusion
In this JavaScript Tutorial, we learned about Arithmetic Increment Operator, its syntax, and usage with examples.