Hoisting in JavaScript

This behavior can surprise beginners to JavaScript, and also, I admit, people like me who learned JavaScript by doing.So what is hoisting about? Concisely put, it means that every variable declared in a scope is actually declared when entering the scope, no matter where you choose to put the declaration.

In the following examples I’m going to create a function to define a scope, but this can be applied to every scope, the global scope, a scope you define with { and }, etc.

functionfoo(){
var bar = true;
foobar = "baz";
var foobar;
}

Even in strict mode, this will work because it is equivalent to

functionfoo(){
var bar,
foobar;
bar = true;
foobar = "baz";
}

It is important to note that only declarations are hoisted, not initializations.

In order to prevent bugs because of this behavior, some developers such as Douglas Crockford recommend that “the var statement should be the first statement in the function body”. I believe this is a bit extreme and it makes the resulting code unorganized. I think it is better to be careful, knowing this rule. You decide.

var, function and function*

As we have just seen; before being initialized, a variable declared with var hold the value undefined.

It is worth noting that function declarations are hoisted, which means that they are not set to undefined.

let, const and class

As we have seen this awful behavior leads to errors. To prevent them, the new ES6 keywords are subject to the TDZ (Temporal Dead Zone). Before the let, const or class statement, instead of being initialized to undefined, variables are actually not initialized.Because something set to undefined may be initialized, remember? It’s just that it has the value undefined.