If we have a loop within a loop, then the
variables declared in the outer loop will
be available in the inner one. In the
following example, the variable num
is available in the inner loop:
for (let i = 0; i <= 9; i++) {
let num = 3;
for (let j = 0; j <= 9; j++) {
console.log(num); // shows 3
}
}
But outside the outer loop, the variable
num
is not available:
for (let i = 0; i <= 9; i++) {
let num = 3;
for (let j = 0; j <= 9; j++) {
}
}
console.log(num); // throws an error
Variables declared in the inner loop are not accessible from the outside:
for (let i = 0; i <= 9; i++) {
for (let j = 0; j <= 9; j++) {
let num = 3;
}
console.log(num); // throws an error
}
console.log(num); // throws an error