Nuance of pre- and post-increment operation in JavaScript

While most of us know and use the ++ and/or -- operator in our code which when used, adds 1 in the case of ++ and deducts 1 if -- but there is a subtle caveat when it comes to its position in the code that I thought is worth noting.

example:

let age = 0;
console.log(age) // expected output 0

console.log(age++) // expected output 0
console.log(age) // expected output 1

In JavaScript, the ++ operator is used for incrementing a variable by 1. When you write age++, it's a post-increment operation, which means the current value of age is used and then age is incremented by 1.

This means given that age initially had the value 0, age++ will first return 0 and then age will be incremented to 1. Here's a step-by-step breakdown:

  1. age has an initial value of 0.
  2. age++ returns the current value of age, which is 0.
  3. After the operation, age is incremented to 1. That's why age++ returns 0 when age initially has the value 0.

If you were to use the pre-increment operator for the same code ++age it would first increment age and then return the incremented value, so ++age would return 1 in this case.

Understanding the subtle difference of where we position this operator greatly helps in avoiding annoying bugs.

the same example using pre-increment:

let age = 0;
console.log(age) // expected output 0

console.log(++age) // expected output 1
console.log(age) // expected output 1

The same rule applies to the -- operator.

JavaScript
Avatar for Fatima Aminu

Written by Fatima Aminu

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.