TOC

The community is working on translating this tutorial into Uzbek, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

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;
alert(a);

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

let a = 9;
a++;
alert(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;
alert(a++);

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;
alert(++a);

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--;
alert(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;
alert(--a);

Summary

The increment/decrement operators provides you with a syntactic shortcut to increment or decrement a value. The value will be returned as a result of this operation, either before modifying it (prefix) or after the modification (postfix).


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!