CodeBlanks Logo Icon CodeBlanks

Assignment operators

JavaScript course · Beginner · Lesson 8/133

Learn shortcut assignments with =, +=, -=, ++ and --.

The assignment operator =

To give a variable a value, you use the = operator. It takes the value on the right and stores it in the variable on the left. For example, let score = 90; makes score hold 90.

Assignment is not one-time; you can give the same variable a new value later: score = 85;. The let keyword is used only for the first declaration, not for later updates.

Compound assignment

When you update a variable, you can avoid writing it twice by using a compound assignment operator. score += 5 means the same as score = score + 5; it is just shorter.

Likewise -=, *=, /= and %= work. Most updates end up in this compact form. Also ++ adds one and -- subtracts one.

Exercise Update the stock counter

Declare stock with an initial value of 20. Then add 5 using the += operator.

Show example solution
// Declare and update the stock variable
let stock = 20;
stock += 5;

Test yourself

  1. What does count += 3 do?

    let count = 10;
    count += 3;
    console.log(count);
    • Adds 3 to count (becomes 13)
    • Sets count to 3
    • Sets count to 30
    • Throws an error
    Show answer

    Adds 3 to count (becomes 13) — Correct. The += operator adds the right side to the current value; count becomes 10 + 3 = 13.

  2. Increment the counter by one

    let visits = 7;
    visits____;
    console.log(visits);
    Show answer
    let visits = 7;
    visits++;
    console.log(visits);
  3. Match the assignment operator

    =
    Assign a value
    +=
    Add and assign
    -=
    Subtract and assign
    ++
    Increment by one

All lessons in Beginner