Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Changing a Variable's Value

A program runs one statement after another, from top to bottom. That's why a variable can have different values at different moments. To change the value of a variable, store a new one in it with =:

let writer = "Edgar Allan Poe";
console.log("The best writer is", writer);
writer = "William Shakespeare";
console.log("The best writer is", writer);

This prints:

The best writer is Edgar Allan Poe
The best writer is William Shakespeare

When the first console.log() runs, writer holds "Edgar Allan Poe". The next line replaces this value with "William Shakespeare", and the old value is gone. So the second console.log() prints the new value.

Notice that there is no let on the third line. You write let only once, when you create the variable. If you wrote it again, JavaScript would stop with the error SyntaxError: Identifier 'writer' has already been declared, which means that a variable with this name already exists.

The new value can be calculated from the current one:

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

This prints:

15

In math, score = score + 5 would make no sense. In JavaScript, though, it means “score gets score + 5”: JavaScript first calculates the right side with the current value (10 + 5), and then stores the result, 15, in score.

Instructions

  1. 1

    The player has lost a life. Below the existing code, change the value of lives to 2 and print it again in the same way. The program should print:

    Lives: 3
    Lives: 2
  2. 2

    Then the player finds an extra life. Below, add one to lives using its current value: lives = lives + 1;

  3. 3

    Print lives once more in the same way. The last line of the output should be Lives: 3.

Back

5/15

  1. 1. Printing
  2. 2. Arithmetic Operations
  3. 3. Comments
  4. 4. Variables
  5. 5. Changing a Variable's Value
  6. 6. Quiz: The Order of Commands
  7. 7. Constants
  8. 8. Division and Remainder
  9. 9. Joining Text
  10. 10. Text and Numbers
  11. 11. Quiz: Text and Numbers
  12. 12. Template Literals
  13. 13. Quiz: Template Literals
  14. 14. Reading Errors
  15. 15. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.