let, const and template literals

A variable is a name you stick on a value so you can use it later. JavaScript gives you two ways to make one:

const name = "Ada";
let score = 0;
  • const means the name always points at the same value. Try to reassign it and you get an error.
  • let means you are allowed to change it later: score = score + 10;

Which one should you use? Start with const every time. Switch to let only when you actually need to change the value. That way, when you read const, you know that value never moves, which makes code easier to follow. (You may also see var in old tutorials. It is the older way and has some weird behaviour; skip it.)

Names can use letters, digits, _ and $, but cannot start with a digit. The convention is camelCase: highScore, playerName. Names are case sensitive, so score and Score are two different variables.

Updating a number has shortcuts: score += 5 means score = score + 5, and score++ adds one.

Template literals

Gluing strings with + gets ugly fast. Template literals use backticks instead of quotes, and let you drop values straight in with a dollar sign and curly brackets:

const player = "Sam";
const lives = 3;
console.log(`${player} has ${lives} lives left`);

That prints Sam has 3 lives left. Anything inside the curly brackets is real JavaScript, so you can even do maths in there. The backtick key is usually at the top left of your keyboard, hiding under Esc.

Try it yourself

Edit it. Break it. Run it again.
const name = "Ada";
let score = 0;
console.log(name, score);

score = score + 10;
score += 5;
score++;
console.log(`${name} now has ${score} points`);
console.log(`Double that is ${score * 2}`);
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Fix the counter

This code crashes with "Assignment to constant variable". Fix it so score ends up as 15.

const score = 10;
score = score + 5;
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2Build a message

Use the two variables and a template literal to print exactly: Mia is 14 years old

const name = "Mia";
const age = 14;
console.log("name is age years old");
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.