Why is it considered best practice?

Aladdin :

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

Elias Soares :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=336621&siteId=1