Shorter Notation

In loops, you change variables all the time, usually by adding or subtracting something. Writing number = number + 1 over and over gets tiring, so JavaScript has shorter ways to write it:

  • score += 5; means the same as score = score + 5;
  • score -= 5; means the same as score = score - 5;
  • score++; means the same as score = score + 1;
  • score--; means the same as score = score - 1;

Read += as “add to”: score += 5 means “add 5 to score”. The operators ++ and -- are for the most common change of all: one more, or one less.

let score = 10;
score += 5;
console.log(score);
score -= 3;
console.log(score);
score++;
console.log(score);
score--;
console.log(score);

This prints:

15
12
13
12

The += operator works with text too. It adds text to the end of the variable:

let message = "Hello";
message += ", world";
message += "!";
console.log(message);
Hello, world!

With ++, the loop from the previous exercise gets a little shorter. This is how you will see it written most often:

let number = 1;
while (number <= 3) {
    console.log(number);
    number++;
}
1
2
3

Two typical mistakes:

  • score + 5; on its own does nothing. It calculates the result but doesn't store it anywhere, so score doesn't change. You need score += 5;.
  • score =+ 5;, with the two characters swapped, doesn't cause an error. JavaScript reads it as score = +5; and simply stores 5 in score. The equals sign always comes second: +=, -=.

All these shortcuts change the variable, so they only work with let. With const, they end with TypeError: Assignment to constant variable.

Instructions

The loop in the editor prints 0, 10, 20 and so on up to 50. Replace number = number + 10; with the shorter notation using +=. The output stays the same.

Below the loop, create a variable countdown with the value 3 and write a second while loop: while countdown is greater than 0, print countdown and then decrease it by one with --.

After the second loop, print Go!. The output then ends with four lines: 3, 2, 1 and Go!.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

2/12