Defining variables with let and const
Files in this demo
├─ index.html └─ script.js
A variable is a name for a value, so you can use it later without retyping it.
let score = 0;
const name = "Gabriel";
The = means “put this in here”. It is not a statement that the two sides are equal ~ that catches people who remember it from maths.
let vs const
const~ you won’t reassign this name.let~ you will.
Use const by default. Switch to let only when you genuinely need to change the value. It means anyone reading your code (including you, in a month) can see at a glance which values move and which don’t.
You may also see var in older code. It’s the original, it has some strange scoping behaviour, and there’s no reason to write new code with it.
The const gotcha
const list = ["a", "b"];
list.push("c"); // this works!
list = ["x"]; // this does not
const stops you pointing the name at something new. It doesn’t freeze what’s inside. Everyone trips on this once.
The types you’ll use
- Number ~
42,3.14. No quotes. - String ~
"text". Quotes, single or double, just be consistent. - Boolean ~
trueorfalse. - Array ~
["a", "b"]. An ordered list. Count from zero:list[0]is the first item. - Object ~
{ name: "Moonbug" }. Named values. Reach in withobject.name. nullandundefined~ “deliberately nothing” and “never set”.
Naming
Lowercase first letter, capitals for each word after: myScore, catName. Names can’t start with a number or contain spaces. Make them describe what’s in them ~ x tells you nothing.
Click to resume
Use the console below.