Scope in loops in JavaScript

Let's see what scope variables have when working with loops. Let's declare some variable inside the loop:

for (let i = 1; i <= 9; i++) { let num = 3; console.log(num); // shows 3 }

If we try to display this variable outside the loop, we will get an error:

for (let i = 1; i <= 9; i++) { let num = 3; } console.log(num); // will throw an error

If necessary, you can declare a variable outside the loop - then it will be available both inside the loop and outside:

let num; // declare the variable outside the loop for (let i = 1; i <= 9; i++) { num = 3; // set it to the value } console.log(num); // shows 3
enru