In this lesson, you kept score for a board game in a script, score.js, and updated a name from its own current value.
Key Points
- JavaScript works through an update in two steps. First it works out the right side, using the value the name points at right now. Only then does the name on the left move to the result.
- You create the name once with
let. The update lines have nolet, because the name already exists and you’re moving it, not creating it again. - A script runs from top to bottom, so each update starts from wherever the name points at that moment. Starting at
20, adding10and then5gives30, then35. That’s a running total. - A calculation on its own, like
score + 10with nothing in front of it, changes nothing. JavaScript works out30and throws it away, andscorestill points at20. To keep a result, point a name at it.
The Final Code
score.js
let score = 20;
score = score + 10;
console.log(score);
score = score + 5;
console.log(score);
$ node score.js
30
35
The experiment with a calculation on its own:
experiment.js
let score = 20;
score + 10;
console.log(score);
$ node experiment.js
20
Next up is How On-Site Exercises Check Your Code.