Photo by Jon Tyson on Unsplash

Smooth Operators

JavaScript Increment/Decrement Operators — Prefix vs. Postfix

Jamie Berrier
2 min readJan 16, 2021

--

The increment and decrement operators are used to change a variable’s value by 1. The increment operator (++) increases the value by 1 and the decrement operator ( —- ) decreases the value by 1.

Prefix

If used prefix (++i or --i): FIRST, the variable’s value is changed THEN, the variable is used. It returns the value AFTER incrementing/decrementing.

let count = 7console.log(++count)// 8

Postfix

If used postfix (i++ or i--): FIRST, the variable is used THEN, the variable’s value is changed. It returns the value BEFORE incrementing/decrementing.

let count = 7console.log(count++)// 7

What makes these operators so smooth?

Let’s look at a JavaScript while statement example: while count > 0, console.log(`The count is ${count}`) and decrementcount by 1.

We can refactor decrementing count (line 6) with the decrement operator. While could just change line 6, we can make the code more succinct by decrementing inside the console.log().

The value of count is logged to the console and THEN decremented. What happens if we use the pre-decrement operator instead?

The output is different! Remember, when the decrement operator is used prefix, the value is changed BEFORE it is logged to the console. Therefore, the value of count is decremented and THEN logged to the console.

Prefix or Postfix

To help keep these smooth operators straight, just remember:

  • Prefix: returns the value AFTER incrementing/decrementing.
  • Postfix: returns the value BEFORE incrementing/decrementing.

--

--