In vanilla JS, some operators—such as the increment (++) and decrement (--) operators—can be used either prefix or postfix. But when does it matter?

When used prefix (++x), the increment operator increments the value first before returning it. When used postfix (x++), the increment operator returns the value first before incrementing it. The same applies to the decrement operator.

Let's borrow some examples from the MDN Web Docs to see this in action.

Prefix

let a = 2;
let b = ++a;

// a === 3
// b === 3

Postfix

let x = 3;
let y = x++;

// x === 4
// y === 3

When does it matter?

Most of the time, I find that I don't need the prefix operators. But I recently encountered a situation where it made a crucial difference!

In my US states memory game, I have an array of all 50 states:

const states = [
"alabama",
"alaska",
"arizona",
"arkansas",
"california",
"colorado",
"connecticut",
"delaware",
"florida",
"georgia",
"hawaii",
"idaho",
"illinois",
"indiana",
"iowa",
"kansas",
"kentucky",
"louisiana",
"maine",
"maryland",
"massachusetts",
"michigan",
"minnesota",
"mississippi",
"missouri",
"montana",
"nebraska",
"nevada",
"new hampshire",
"new jersey",
"new mexico",
"new york",
"north carolina",
"north dakota",
"ohio",
"oklahoma",
"oregon",
"pennsylvania",
"rhode island",
"south carolina",
"south dakota",
"tennessee",
"texas",
"utah",
"vermont",
"virginia",
"washington",
"west virginia",
"wisconsin",
"wyoming",
];

I needed to count the number of states beginning with a particular letter. For example, here's how I counted the number of states beginning with 'O':

const numBeginningWithO = states.reduce((count, state) => {
return state.startsWith("o") ? ++count : count;
}, 0);

console.log(numBeginningWithO); // Expected output: 3

The count starts at 0. On each iteration of the states array, the callback function checks if the current state starts with "o". If it does, it returns ++count. Otherwise, it just returns count.

The prefix increment is crucial here, because we need to increment the count before returning it. If we incremented using postfix, then the final output would be 0, because the callback function would return 0 on every iteration!