ECMA Specification Safari: Increment (and Decrement) Operators

Recently, I’ve started reading through the ECMA Script (JavaScript) specification to get a more in depth understanding of the language I seem to be using every day. There are some interesting things I am coming across. Today’s interesting thing is increment and decrement operators.

There are two ways of incrementing a variable (decrementing the variable works in the same way): putting the increment operator before or after the variable.

var prefixIncrementVariable = "4" 
var postfixIncrementVariable = "4"
++ prefixIncrementVariable // returns 5
postfixIncrementVariable ++ // returns 4

What both operators do is convert the variable into a number, and then increment the variable, changing the value of the variable to one plus the original value. The difference between the two is that the prefix increment notation returns the new value of the variable (5 in this case) as a result of the operation, while the postfix increment notation returns the old value of the variable (which is 4) as the result of the operation.

This sounds a bit confusing, but it highlights that the effect of an operation is not necessarily the result of the operation. One can think of it as in the case of a function call. The effect is whatever is done within the function. The result is whatever is returned by the function. Interesting.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s