Hoisting is a behavior of JavaScript to move declarations to the top of the scope, it can be the global or function scope.
There are no these two keywords let
and const
. Let's see how hoisting affects these two new features.
Declaration with let
console.log(hoist);
let hoist = "A variável foi levada ao topo";
Output:
ReferenceError: hoist is not defined
A reference error means that the variable was not in the memory of the computer and does not yet exist, is different from what happens with the var
that would return undefined
.
This ensures that we always have to declare our variables first.
However, an implementation like this results in undefined
and we have to be more attentive:
let hoist;
console.log(hoist);
hoist = "A variavel foi levada ao topo";
Output:
undefined
So, in addition to having to declare the variable before it is used, we also have to initialize it.
Declaration with const
console.log(hoist);
const hoist = "A variavel foi levada ao topo";
Output:
ReferenceError: hoist is not defined
Just like let
the interpreter says that the variable does not exist by casting a ReferenceError
. The same will occur inside a function.
We should also be aware of a statement like this:
const hoist;
console.log(hoist);
hoist = "A variavel foi levada ao topo";
Output:
SyntaxError: Missing initializer in const declaration
This shows us that a constant must be declared and initialized before using.
Completing
JavaScript takes to the top the variables declared with let
and const
of es6, and the difference is how they are initialized.
Variables that are declared with let
or const
are not initialized at the start of execution, although variables declared with var
are initialized with undefined
value.
Sources:
Hosting
Understanding Hoisting in JavaScript