var and Hoisting
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — The Old Keyword: var
When reading older JavaScript code, you will often see variables declared with `var` instead of `let` or `const`. `var` was the original way to create variables in JavaScript, but it has some quirks that can cause tricky bugs. First quirk: `var` ignores `{ }` blocks! A variable declared with `var` inside an `if` or a `for` loop leaks right out of the block and remains accessible afterward:
if (true) {
var escaped = "I leaked out of the if block!";
let stayedInside = "I stay inside the block";
}
console.log(escaped);
// console.log(stayedInside); // Uncomment this line to see the error!Unlike `let` and `const`, `var` only respects function boundaries, never `{ }` blocks. That means a loop counter declared with `for (var i = 0; ...)` stays alive even after the loop is finished:
for (var i = 0; i < 3; i++) {
// loop runs for i = 0, 1, 2
}
console.log("After the loop, i is still: " + i);Exercise 2 — Hoisting: Reading a Variable Too Early
Second quirk of `var`: if you read a `var` variable before the line where it is declared, JavaScript does not throw an error! Instead, it quietly gives you `undefined`:
console.log(score);
var score = 100;
console.log(score);This behavior is called hoisting. Before running your code, JavaScript ”hoists” (lifts) every `var` declaration to the top of its scope and initializes it to `undefined`. The actual value (`100`) is only assigned when execution reaches the `var score = 100` line. With `let` and `const`, reading a variable before its declaration throws a clear error right away—making mistakes much easier to catch:
// console.log(level); // Uncomment this line to see the error!
let level = 5;
console.log(level);Exercise 3 — Function Declarations Are Hoisted Too
Hoisting isn't only a `var` quirk—it also applies to function declarations (`function greet() { ... }`)! When you declare a function with the `function` keyword, JavaScript hoists the entire function to the top of its scope before running the code. That's why you can call `greet()` even on a line above its declaration:
greet();
function greet() {
console.log("Ready to battle!");
}However, an arrow function stored in a `const` (like `const greet = () => { ... }`) follows normal `const` rules: you cannot call it before the line where it is defined.
Exercise 4 — Quiz: var Escapes
What does this code print?
if (true) {
var x = 5;
}
console.log(x);5undefinedHint : This keyword does not care about blocks.
Exercise 5 — Quiz: Read Too Early
What does this code print?
console.log(hp);
var hp = 50;undefined500Hint : The declaration is noted early, but the value is not.
Exercise 6 — Quiz: The let Version
What happens when this code runs?
console.log(hp);
let hp = 50;undefined50Hint : The modern keywords refuse to be read before their line.
Exercise 7 — Trap It Properly
Declare `bonus` so that reading it after the block would be an error.
Hint : One of the keywords respects blocks, and the message must use the variable itself.
Exercise 8 — Summary: Why We Use let and const
Let's recap the three big differences between `var` and `let` / `const`: 1. Block scope: `let` and `const` stay inside `{ }` blocks; `var` ignores blocks and leaks out. 2. Reading before declaration: `let` and `const` throw a helpful error; `var` silently returns `undefined`. 3. Redeclaring the same name: `let` and `const` forbid declaring the same variable twice in the same scope, whereas `var` silently overwrites it:
var name = "Zap";
var name = "Pyrochu";
console.log(name);In modern JavaScript, never write `var` in new code: use `const` by default, and `let` when a variable needs to be reassigned. You only need to recognize `var` when reading older code!
Exercise 9 — var vs let
Match each behaviour with the keyword it describes.
varletvarletExercise 10 — Modernise the Code
An old battle script uses `var` everywhere and leaks its variables. Rewrite it with modern keywords so that nothing escapes its block.
Step 1: rewrite the whole script replacing every `var` with `const`, or `let` when the value really changes. Step 2: keep exactly the same output for the three printed lines. Step 3: at the end, the original script printed the loop counter after the loop. That must now be impossible, so print `"Counter leaked: false"` instead.
Expected output:
Turn 1
Turn 2
Total damage: 60
Counter leaked: false// Old script, rewrite it below
// var total = 0;
// for (var turn = 1; turn <= 2; turn++) {
// var hit = 30;
// total = total + hit;
// console.log("Turn " + turn);
// }
// console.log("Total damage: " + total);
// Write the modern version here