Search code examples
javascriptscopecycle

Why is it considered best practice?


I saw this code on the site w3schools.com (JavaScript Best Practices)

// Declare at the beginning
var i;

// Use later
for (i = 0; i < 5; i++) {

I don’t understand why declaring this variable is considered good practice. It is needed only for the cycle. Why should i make it global


Solution

  • Actually, this code is outdated. The best practice is to use let instead of var (see this question on StackOverflow, and declare it inside the for statement:

    for (let i = 0; i < 5; i++) {
        console.log(i); // 0, 1, 2, 3, 4
    }
    console.log(i); // undefined variable i
    

    The let defines a block scoped variable. This variable won't "bubble" up to the global scope, being more efficient by not polluting the global scope.