Quick Ref: JS Increment & Decrement

JavaScript provides increment and decrement operators so that we can condense our code when increasing and decreasing variables. Those operators are ++ and --.

Both of these lines increment x by 1.

x = x + 1;  
x++;  

Both of these lines decrement x by 1.

x = x - 1;  
x--;  

These operators are used all the time in loops.

for (var i = 0; i < array.lengh; i++)  
for (var i = array.length-1; i > 0; i--)  

Placing the increment or decrement operator after the variable causes the variable to be modified after evaluating the expression. For example, in the for loop, i is incremented after the first pass through the for loop. In the example below, length is the last index of the array + 1.

storage[length] = value; // adds value to the end of the array  
length++; // increase length

storage[length++] = value; // does the same thing  

Moving the operator before the variable modify the variable before the expression is evaluated. In this example, we're removing the last item in the array. We need to decrease length and also access the length - 1 item in the array.

length--;  
var pop = storage[length]; // saves value of the last item  
delete storage [length]; // deletes the popped value

var pop = storage[--length]; // does the same thing  
delete storage[length];  

Operator before the variable = variable modified first.
Operator after the variable = variable modified after.

Happy coding!