HTML / CSS / JavaScript Tutorial

JavaScript Operator: increment

[this page | pdf | back links]

In JavaScript, the ++ operator is the (unary) arithmetic operator for incrementing, i.e. adding one to the variable. There are technically two different increment operators, the prefix one, and the postfix one.


For example, if x is 8 then the statement y = ++x results in x being incremented to 9 and then y assigned this value (i.e. is assigned 9). However, the statement y = x++ involves y being assigned the value of x (i.e. 8) and x then being incremented to 9.


For code clarity, some commentators suggest using the statements x = x + 1; y = x; instead of y = ++x and y = x; x = x + 1; instead of y = x++.



<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<style>table,th,tr,td {border: 1px solid black;
  border-collapse: collapse;}</style>
JavaScript arithmetric increment operator (prefix and postfix)<br><br>
<th>Resulting value of <code>x</code></th>
<th>Resulting value of <code>y</code></th>
<td><code id="IncrementPrefixExample"></code></td>
<td><code id="IncrementPrefixx"></code></td>
<td><code id="IncrementPrefixy"></code></td>
<td><code id="IncrementPostfixExample"></code></td>
<td><code id="IncrementPostfixx"></code></td>
<td><code id="IncrementPostfixy"></code></td>

document.getElementById("IncrementPrefixExample").innerHTML =
  'var x = 8;<br>' +
  'var y = ++x;';
var x = 8; var y = ++x;
document.getElementById("IncrementPrefixx").innerHTML = x;
document.getElementById("IncrementPrefixy").innerHTML = y;
document.getElementById("IncrementPostfixExample").innerHTML =
  'var x = 8;<br>' +
  'var y = x++;';
x = 8; y = x++;
document.getElementById("IncrementPostfixx").innerHTML = x;
document.getElementById("IncrementPostfixy").innerHTML = y;


Contents | Prev | Next | JavaScript Operators

Desktop view | Switch to Mobile