Block Scope: Your Closet

Grade 9, page 4 of 11. A one-minute read.

Variables created with let or const inside any pair of curly braces (an if block, a loop, or even just a plain { } block) only exist inside those braces. This is called block scope:

JavaScript
const temperature = 35;

if (temperature > 30) {
  const advice = "Stay hydrated!";
  console.log(advice);
}

console.log(typeof advice);

It prints

Stay hydrated!
undefined

The same applies to loop counters. The i in a for loop only exists inside the loop:

JavaScript
for (let i = 0; i < 3; i++) {
  console.log(`Inside the loop, i is ${i}`);
}

console.log(typeof i);

It prints

Inside the loop, i is 0
Inside the loop, i is 1
Inside the loop, i is 2
undefined
TipDeclare variables in the smallest scope possible

A good habit: create each variable in the smallest scope where it's needed. If a variable is only used inside a loop, create it inside the loop. This keeps your code tidy and stops variables from being accidentally used (or changed) somewhere they shouldn't be.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning