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:
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:
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
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.