Unit 4 · Thinking like a programmer
let vs const in JavaScript
Use const for a box you fill once and never refill. Use let for a value that will change, such as a counter. Reassigning a const throws an error.
The mix-up
What people often think
“const and let are the same kind of box.”
What the tutor says
A const box is sealed once filled, so refilling it is an error. Use let for a value that changes.
How it works
Defaulting to const is a good habit: when you see let, you know the value is meant to change, and an accidental reassignment of a const is caught straight away.
const seals the box, not necessarily what is inside it. A const array can still have items pushed into it; you just cannot replace it with a different array.
Side by side
const visits = 0;
visits = visits + 1; // TypeError: Assignment to constant variablelet visits = 0;
visits = visits + 1;Practise it with a tutor watching
Variables are labelled boxes
Store values in variables, update them, and tell assigning apart from comparing.
Free, no account needed.