2 minutes read

In this topic, we will discuss two of the most commonly used operators in programming — increment and decrement. These operators are present in many programming languages, including JavaScript. They are used to efficiently increase or decrease the value of a variable by one. In numerous programming tasks, it is required to modify the value of a variable in this manner, making knowledge of increment and decrement operators fundamental.

++ and -- in JavaScript

JavaScript has two opposite operations called increment (++) and decrement (--) to increase or decrease the value of a variable by one, respectively. For example:

let a = 10;
let b = 10;
console.log(++a); // 11
console.log(--b); // 9

The code above actually gives the same result as the code below:

let a = 10;
let b = 10;
console.log(a + 1); // 11
console.log(b - 1); // 9

Prefix increment

Both operators have two forms that are very important when using the result in the current statement:

  • prefix (++n or --n) increases/decreases the value of a variable before it is used;
  • postfix (n++ or n--) increases/decreases the value of a variable after it is used.

Let's look at the prefix increment:

let a = 4;
let b = ++a;
 
console.log(a); // 5
console.log(b); // 5

In this case, the value of a has been incremented and then assigned to b. So, b is 5.

Postfix increment

Postfix increment increases or decreases the value of a variable after it is used. Consider an example:

let a = 4;
let b = a++;

console.log(a); // 5
console.log(b); // 4

The Postfix operator first returns the value of a and only then the variable a is incremented.

That's why when we assign a++ to b, we assign 4 to b, only then a will be incremented. So, b is 4 and a is 5.

If that's still not clear enough for you, take a look at the code:

let a = 4;
console.log(a++ - a); // -1

Conclusion

JavaScript has two operators, increment and decrement, which can be used to increase or decrease the value of a variable by one. These operators have two forms of recording: prefix and postfix. The prefix form changes the variable before using it, while the postfix form changes it after using it. Although these operators are helpful, it is important not to overuse them as it can negatively impact the readability of your code.

390 learners liked this piece of theory. 17 didn't like it. What about you?
Report a typo