JavaScriptLesson 2 of 16
Variables: let and const
A variable is a labelled box where a program keeps a value. JavaScript has two kinds: const for contents that stay put and let for contents that will change.
Key points
- const name = "Mia": the value cannot be reassigned
- let coins = 10: later you can write coins = 12
- coins += 5 is short for coins = coins + 5
- Names use camelCase, like playerName or totalPrice, and case matters
- var is the old way to declare variables; modern code leaves it out
Example
const city = "Rome";let temperature = 24;temperature = 27; // let can changeconsole.log(city, temperature); let visits = 1;visits += 1; // the same as visits = visits + 1console.log(typeof city, typeof visits, visits);// city = "Paris"; → TypeError: Assignment to constant variable.temperature changed because it was declared with let. Remove the // on the last line and the program crashes: a const cannot be reassigned. typeof tells you the type of a value.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Mia opens a chest with 5 coins and then buys a potion for 3. Change coins so that the program prints Mia has 12 coins.
Output
What your program prints appears here.