++i and i++

These increment operators and the corresponding decrement operators are perhaps a little confusing to anyone who hasn't come across them before.

To start with there are several different ways to add or subtract one.


i = i + 1;
i += 1;
i++;
++i;

For subtracting one there are the same four choices with - substituted for each +.

So why exactly does JavaScript (and other languages) provide so many different ways to do the same thing?

Well for one thing some of these alternatives are shorter than others and so involve less typing. Using += easily allows any number and not just one to be added to a variable without having to enter the variable name twice.

That still doesn't explain why both i++ and ++i exist since both can only be used to add one and both are the same length. The reason for the two alternatives is that these are not really intended to be used as stand alone statements but are really designed to be able to be incorporated into more complex statements where you actually update more than one variable in the one statement.

Probably the simplest such statement is as follows:


j = i++;

This statement updates the values of both of the variables i and j in the one statement. The thing is that while ++i and i++ do the same thing as far as updating i is concerned they do different things with regard to updating other variables.

The above statement can be written as two separate statements like this:


j = i;
i += 1;

Note that combining them together means we have eight characters instead of 13. Of course the longer version is much clearer where it comes to working out what value j will have.

Now if we look at the alternative:


j = ++i;

This statement is the equivalent of the following:


i += 1;
j = i;

This of course means that j now has a different value to what it had in the first example. The position of the ++ either before or after the variable name controls whether the variable gets incremented before or after it gets used in the statement that it is used in.

Exactly the same applies when you consider the difference between --i and i-- where the position of the -- determines whether one is subtracted before or after the value is used.

So when you use it separately as a single statement it makes no difference whether you place it before or after the variable name (except for a microscopic speed difference that no one will ever notice). It is only once you combine it with another statement that it makes a difference to the value that gets assigned to some other variable or variables.