The Increment operator (++
) increments its operand by one.
`// postfix
var a = 5; // 5
var b = a++; // 5
var c = a // 6`
In this case, a
is incremented after setting b
. So, b
will be 5, and c
will be 6.
`// prefix
var a = 5; // 5
var b = ++a; // 6
var c = a; // 6`
In this case, a
is incremented before setting b
. So, b
will be 6, and c
will be 6.
The increment and decrement operators are commonly used in for
loops, for example:
for (var i = 0; i < 42; ++i)
{
// do something awesome!
}
Notice how the prefix variant is used. This ensures that a temporarily variable isn’t needlessly created (to return the value prior to the operation).