DEV Community

Discussion on: Have you heard about hoisting in Javascript? This is what it is.

Collapse
 
dystroy profile image
Denys Séguret • Edited

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.

Collapse
 
_ferh97 profile image
Fernando Hernandez

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.