JavaScript hoisting
In Chapter 6, Functions, we discussed that we have three different variables, const
, let
, and var
, and we highly recommended that you should use let
instead of var
because of their different scopes. JavaScript hoisting is why. Hoisting is the principle of moving declarations of variables to the top of the scope in which they are defined. This allows you to do things that you cannot do in many other languages, and for good reason by the way. This should look normal:
var x;
x = 5;
console.log(x);
It just logs 5
. But thanks to hoisting, so does this:
x = 5;
console.log(x);
var x;
If you try to do this with let
, you'll get a ReferenceError
. This is why it is better to use let
. Because clearly, this behavior is very hard to read, unpredictable, and you don't really need it.
The reason this happens is that the JavaScript interpreter moves all the var
declarations to the top of the file before processing the file. Only the declarations...