Increment and Decrement: ++ and --

Grade 3, page 4 of 11. A one-minute read.

Adding or subtracting exactly one is so common (counting things, moving to the next item, losing a life in a game) that it has its own special operators:

JavaScript
let lives = 3;
lives--;
console.log(lives);

let likes = 99;
likes++;
console.log(likes);

It prints

2
100
  • ++ adds one (increment)
  • -- subtracts one (decrement)

likes++ does exactly the same thing as likes += 1 or likes = likes + 1. Three ways to say the same thing! Programmers love options. And arguing about which option is best.

Professor’s CornerBefore or after?

You can write ++ before or after the variable: count++ or ++count. On a line by itself, there's no difference. But if you use it inside a bigger expression, there is: count++ gives you the old value and then adds one, while ++count adds one first and gives you the new value.

JavaScript
let count = 5;
console.log(count++);
console.log(count);
console.log(++count);

It prints

5
6
7

This is confusing even for experienced developers, so our advice is: only use ++ and -- on a line by themselves. Then you never have to think about it.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning