Lesson 2 of 28
In progress
Variables: const, let and the end of var
Declare values with const and let, understand block scope, and learn why var belongs in old code rather than new.
JavaScript gives you three ways to declare a variable and only two of them belong in new code. The choice between const and let is a statement about whether the value should change.
What you will learn
- Declare variables with
constandlet. - Explain block scope and why it prevents bugs.
- Recognise the cases where
constdoes not mean immutable.
Two declarations, one rule
Use const by default. Switch to let only when you must reassign.
Editable. Runs in your browser.
completed = completed + 1;
console.log(course, completed);
// course = "Python"; // TypeError: Assignment to constant variable.
Press Run to see the output.
const prevents reassignment of the binding. It does not freeze the value: an object or array declared with const can still be changed.
Editable. Runs in your browser.
const scores = [72, 88];
scores.push(91);
console.log(scores);
Press Run to see the output.
That is not a loophole; it is the difference between "this name always points at this object" and "this object can never change". Rebinding the name is what const forbids.
Block scope
let and const are scoped to the nearest block, which is a pair of braces. A variable declared inside an if or a loop does not exist outside it.
Editable. Runs in your browser.
// console.log(inside); // ReferenceError
Press Run to see the output.
Block scope is why let fixed the classic loop bug. With var, the loop variable was shared by every iteration, so callbacks created inside the loop all saw the final value. With let, each iteration gets its own binding.
Editable. Runs in your browser.
for (var j = 1; j <= 3; j++) {
setTimeout(() => console.log("var:", j), 0);
}
Press Run to see the output.
The first loop prints 1, 2, 3. The second prints 4, 4, 4, because var is function-scoped and the callbacks run after the loop finished. That difference alone justifies dropping var from new code. It is also why a callback created inside a let loop sees the value from its own iteration, which is the behaviour most people expect before they learn anything about scope.
Naming
Names may contain letters, digits, _ and $, and cannot start with a digit. They are case-sensitive: total and Total are different variables.
Use camelCase for variables and functions, PascalCase for classes, and UPPER_SNAKE_CASE for values that are genuinely constant across the program. A name should say what the value means: remainingAttempts beats n.
Avoid names that shadow browser globals such as name, status or top. They are legal, and they cause strange behaviour because the global still exists in some contexts.
Declaration, initialisation and hoisting
A const must be initialised when declared. let may be declared and assigned later, though doing so usually hurts readability.
Both are hoisted to the top of their block but stay in a temporal dead zone until the declaration runs. Accessing one earlier throws ReferenceError rather than returning undefined. That is stricter than var and catches mistakes earlier.
Editable. Runs in your browser.
let later = 5;
Press Run to see the output.
The try prints ReferenceError. The point is not to write code like this, but to recognise the message when a variable is used above its declaration.
When a value should not change
If a function receives a configuration object and must not modify it, const protects the binding but not the contents. Copy before changing:
Editable. Runs in your browser.
console.log(defaults.pageSize);
console.log(custom.pageSize);
Press Run to see the output.
{ ...defaults } creates a shallow copy. Nested objects are still shared, which matters once configuration gets deep. The next module covers copying properly.
Declaring with const and then trying to reassign inside an if produces TypeError: Assignment to constant variable at runtime, not when the file loads. If a value genuinely changes, declare it with let at the point where it is first known, not at the top of the file.
Create a const for a site name and a let for a visitor count. Add three to the count and log both. Then try to reassign the site name inside a try block and log the error name.
Show solution
Editable. Runs in your browser.
visitors += 3;
console.log(siteName, visitors);
try {
siteName = "Other";
} catch (error) {
console.log(error.name);
}
Press Run to see the output.
The count changes because it was declared with let. Reassigning the const throws a TypeError, captured by the catch, which prints TypeError.
Recap
- Prefer
const; useletonly when the binding must change. constprotects the binding, not the object’s contents.letandconstare block-scoped;varis function-scoped and should be avoided.
Next, you will look at the primitive types and the coercions that surprise people.
Is const faster?
Can I declare a variable without a keyword?
Progress is saved in this browser only. No account, no email.