7
In the MDN Variables section we have the following statement:
For that Reason, it is Recommended to Always declare variables at the top of their Scope (the top of global code and the top of Function code) so it’s clear which variables are Function scoped (local) and which are resolved on the Scope chain.
This excerpt says that it is recommended to always declare variables at the top of its scope due to the fact that Javascript has the behavior of variable Hoisting.
What are the implications of not following this recommendation? Particularly, I find a code much easier to read when the declaration of its variable is performed at the exact moment before its first use, compared to declaring all variables at the beginning of the execution of a function, for example.
Exemplifying:
// Declarando variável no topo de seu escopo
function(){
var a = 0, b = 0;
//some code
a = 5;
//some code
b = 10;
}
//Declarando variável próximo de sua utilização
function(){
//some code
var a = 0;
a = 5;
//some code
var b = 0;
b = 10;
}
In comparison to what?
– Maniero
I believe that this recommendation is due to standard reading and maintenance of the code. Imagine a script with 200 lines, where a variable is used on the 180 line and whoever is updating needs to change the initialization of the variable from array to object. In that case you’ll have to hunt down the statement.
– BrTkCa
@bigown updated question
– Vinícius
@Lucascosta if the function has 200 lines, the problem is another.
– Maniero
Even if the function has 200 lines, if it creates 10 variables, it is no longer difficult to read and maintain its variables with all of them initialized in the first line of the function?
– Vinícius
@bigown with scope understood global scope. In fact, a function with 200 lines the problem is another :)
– BrTkCa
@Lucascosta is that global scope ends up being problem tb. And then I agree that if you go this way, declare before is useful.
– Maniero