I disagree with "The solution is to declare your variables at the beginning of your code".
Because the "code" which matters for hoisting is the function while in many cases the meaningful scope you'd want is a block, for example.
... // localThing is defined here
if (condition) {
var localThing = ...
do something with localThing
}
... // localThing is defined and valued here
Coders not familiar enough with hoisting might fail to see that the scope of localThing starts before this block and ends later: it covers the whole function.
Declaring value at the beginning of the enclosing function while it's used only in a block would be a bad practice.
The real solution in 2019 isn't to declare your variables at the beginning of your function but to use let to declare them where they are needed, especially in inner non functional blocks. let has been defined to fix the problems of var, use it, especially if you're young to JavaScript and don't already know all of its many traps.
Hey Denis Seguret thanks for your feedback. Probably I don't was very specific with that. You are right, by saying that 'the solution is to declare your variables at the beginning of your code' I was meant to declare them in the beginning of the scope you are in. Also, for sure is a good practice to always use let instead of var, because when you defined a variable using var is available in the global scope. I think I will update it. I assumed the scope concept was understand it.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I disagree with "The solution is to declare your variables at the beginning of your code".
Because the "code" which matters for hoisting is the function while in many cases the meaningful scope you'd want is a block, for example.
Coders not familiar enough with hoisting might fail to see that the scope of
localThing
starts before this block and ends later: it covers the whole function.Declaring
value
at the beginning of the enclosing function while it's used only in a block would be a bad practice.The real solution in 2019 isn't to declare your variables at the beginning of your function but to use
let
to declare them where they are needed, especially in inner non functional blocks.let
has been defined to fix the problems ofvar
, use it, especially if you're young to JavaScript and don't already know all of its many traps.Hey Denis Seguret thanks for your feedback. Probably I don't was very specific with that. You are right, by saying that 'the solution is to declare your variables at the beginning of your code' I was meant to declare them in the beginning of the scope you are in. Also, for sure is a good practice to always use let instead of var, because when you defined a variable using var is available in the global scope. I think I will update it. I assumed the scope concept was understand it.