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 ShakespeareWhen 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:
15In 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
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: 2Then the player finds an extra life. Below, add one to lives using its current value: lives = lives + 1;
Print lives once more in the same way. The last line of the output should be Lives: 3.