1

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

Aladdin
  • 28
  • 1
  • 3
  • 3
    Well it's not. You should be avoid global variable and w3schools as well ( pun intended ). Use MDN for better explained and updated reference – Code Maniac Mar 20 '20 at 16:00
  • 2
    It would be global anyway (var doesn't create a block scope). This is (or was) actually a recommendation of var declarations, which are best to declare at the beginning of their scope (not ncecessarily global), because the declarations are hoisted anyway, and later declarations are ignored. – Teemu Mar 20 '20 at 16:01
  • 2
    w3schools has improved, but for a long time it has displayed quite wrong informaiton. I wouldn't trust w3schools for best pratices. Use `let` instead of `var`in this case, at least. – Pac0 Mar 20 '20 at 16:02
  • Yes, but it can be replaced by `let` – Aladdin Mar 20 '20 at 16:03
  • 1
    if you are looking for any best practice on javascript use [MDN](https://developer.mozilla.org/en-US/docs/Web/Tutorials) – ROOT Mar 20 '20 at 16:04
  • Thanks to everyone. Until this moment, I doubted, but now I understood – Aladdin Mar 20 '20 at 16:07

2 Answers2

2

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.

Elias Soares
  • 9,884
  • 4
  • 29
  • 59
0

According to w3schools.com:

It is a good coding practice to put all declarations at the top of each script or function.

This will:

Give cleaner code Provide a single place to look for local variables Make it easier to avoid unwanted (implied) global variables Reduce the possibility of unwanted re-declarations

You can do it to make the code more cleaner. But I recommend using let instead of var.

MARSHMALLOW
  • 1,315
  • 2
  • 12
  • 24