Operators:

Increment/decrement operators

In the previous article, we talked about arithmetic operators in JavaScript - the ability to do calculations. With that in mind, I want to introduce you to another type of operator: The increment and decrement operators.

They are what you could call syntactic sugar - you could live without them, but they are nice to have and used in a lot of code you may find on the Internet.

The increment operator: ++

Let's say that you have a variable and you want to add one to it. We can simply use the addition operator, as we saw in the previous article:

``````let a = 9;
a = a + 1;

But using the increment operator (++) instead, we save a few keystrokes, but achieving the exact same thing:

``````let a = 9;
a++;

Prefix/postfix increment

The increment operator can be used inside a statement as well, allowing us to do the same as above, but with a line of code less:

``````let a = 9;

But if you run this example, you will see that it's actually not the same result. In the initial example, we got the value 10 alerted, but now we get 9. Why? Because we used the postfix variant, where the increment operator is placed after the variable name. When doing that, we get the value returned right before the value is added to it. We can change this very simply though, by moving the operator:

``````let a = 9;

This is the prefix variant, which will return the value AFTER the addition has been performed.

The decrement operator: --

So adding one with the increment operator is easy, but what if we want to do subtraction instead? I'm sure you already guessed it, but there's an operator for that as well, called the decrement operator. It works just like the increment operator, but will do subtraction instead of addition.

``````let a = 11;
a--;

Prefix/postfix decrement

And of course, we have both a prefix and a postfix variant of the decrement operator as well:

``````let a = 11;