Block Scope (let and const)
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Variables Inside a Block
Functions are not the only places that create their own scope. Every pair of curly braces `{ }` in an `if` statement or a loop creates a block. When you declare a variable with `let` or `const` inside a `{ }` block, it only exists inside that block. Trying to read it outside throws an error:
const isCritical = true;
if (isCritical) {
const bonus = 50;
console.log("Critical hit! +" + bonus);
}
console.log(bonus); // error!This rule is called block scope: variables declared with `let` or `const` stay locked inside the `{ }` curly braces where they were created.
Exercise 2 — Blocks in Loops and Conditions
Block scope applies to every control structure with curly braces `{ }`: `if`, `else`, `for`, and `while`. In a `for (let i = 0; ...)` loop, both the loop counter `i` and any variable declared inside the `{ }` body belong strictly to the loop and disappear as soon as it ends:
for (let i = 0; i < 3; i++) {
const step = i + 1;
console.log("Turn " + step);
}
// console.log(i); // Uncomment this line to see the error!That's why you can write several `for (let i = 0; ...)` loops in the same file without `i` ever clashing! And just like functions, code inside a block can still read variables declared outside the block:
const name = "Zap";
if (true) {
console.log(name + " enters the arena!");
}Exercise 3 — Declaring a New Variable vs. Reassigning
Pay close attention to whether you write `let` inside a block or not! If you write `let level = 99` inside a block when an outer `level` already exists, you create a brand-new variable just for that block. It temporarily hides (or shadows) the outer variable without changing it:
let level = 5;
if (true) {
let level = 99;
console.log("Inside block: " + level);
}
console.log("Outside block: " + level);On the other hand, if you write `level = 99` without `let`, you are not creating a new variable—you are reassigning the outer `level` variable:
let level = 5;
if (true) {
level = 99;
}
console.log("Outside block: " + level);Exercise 4 — Quiz: After the Block
What happens on the last line?
if (true) {
const bonus = 10;
}
console.log(bonus);10undefinedHint : The braces mark the borders of the variable's life.
Exercise 5 — Quiz: Hidden or Changed?
What does the last line print?
let hp = 100;
if (true) {
let hp = 20;
}
console.log(hp);10020undefinedHint : Look at whether a new variable was declared inside the block.
Exercise 6 — Quiz: Without the Keyword
What does the last line print?
let hp = 100;
if (true) {
hp = 20;
}
console.log(hp);20100undefinedHint : With no declaration, which variable does the assignment reach?
Exercise 7 — Protect the Outer Value
Make the block use its own `hp`, leaving the outer one at 100.
Hint : One keyword creates a brand-new variable instead of touching the existing one.
Exercise 8 — let and const Share the Same Scope
Both `let` and `const` are block-scoped: they obey the exact same `{ }` visibility rules. The only difference between them is whether the variable can be reassigned (`=`) later: - Use `const` when the variable will never be reassigned. - Use `let` when you need to update the variable's value later (like a counter or a changing score).
if (true) {
let turns = 1;
const maxTurns = 10;
turns = 2;
console.log("Turn " + turns + " / " + maxTurns);
}Exercise 9 — Block Scope Cheat Sheet
Match each situation with what happens.
Exercise 10 — Critical Hit Bonus
Compute a battle turn where a bonus only exists when the hit is critical, keeping every temporary value inside the smallest block possible.
Step 1: `attack(base, critical)` starts with a local `total` equal to the base. Step 2: inside an `if (critical)` block, declare a local `bonus` worth the base, add it to `total`, and print `"Critical hit! +X"`. Step 3: after the block, return `total`. Step 4: print the result of a critical attack with base 30, then of a normal attack with base 30. Finish by printing `"Turns: N"` using a counter declared outside the function and increased at each call.
Expected output:
Critical hit! +30
60
30
Turns: 2let turns = 0;
// Write your function here
// Use it here