What is the difference between prefix and postfix operators?

Angelos Chalaris · Oct 31, 2021 ·

JavaScript, Math

The increment operator (++) adds 1 to its operand and returns a value. Similarly, the decrement operator (--) subtracts 1 from its operand and returns a value. Both of these operators can be used either prefix (++i, --i) or postfix (i++, i--).

If used prefix, the value is incremented/decremented, and the value of the expression is the updated value.

let i = 0;    // i = 0
let j = ++i;  // i = 1, j = 1
let k = --i;  // i = 0, k = 0

If used postfix, the value is incremented/decremented, and the value of the expression is the original value.

let i = 0;    // i = 0
let j = i++;  // i = 1, j = 0
let k = i--;  // i = 0, k = 1

Recommended snippets

  • toRomanNumeral

    JavaScript, Math

    Converts an integer to its roman numeral representation. Accepts value between 1 and 3999 (both inclusive).

  • When working with numeric arrays in JavaScript, you might find yourself in need of finding the minimum or maximum value. Here's a quick and easy way to do it.

  • to_roman_numeral

    Python, Math

    Converts an integer to its roman numeral representation. Accepts value between 1 and 3999 (both inclusive).