Hoisting
Last updated
Last updated
Let's start with example 1 (len)
The result is not unusual: raised error a is not define
, because the variable a
has not been declared anywhere
Example 2:
This example seems "a lot" more complicated than the above example but the result is still the same:a is not define
Example 3:
The output will be undefined
because a
it has been declared but has not yet been assigned a value
Example 4
By chance and surprisingly, the results were the same as Ex3
, both undefined
Why is that so???
Hoisting is the default action of Javascript, it will move the declaration to the top. In Javascript, a variable can be declared after being used.
We will continue Ex5
and explain more clearly for example 4.
The results will be interpreted according to the following diagram: Explanation:
The Javascript compiler will separate the section var a = 'Hello Hoisting'
into two parts: declaration and value assignment
Declare:var a
Assign valuea = 'Hello Hoisting'
According to Hoisting, Javascipt will move the declaration to the top. Therefore, only the declaration part will be moved to the top, while the value assignment part will remain in the same order so it will remain at the bottom. So the Output will beundefined
The Javascript compiler will move the declaration to the top just like it does with variables. Example 6:
Output is the same as with the variable partYOLO
Example 7:
The results will be interpreted according to the following diagram:
Explain:
Just like with part 1, the internals of the function do_something
are also used by the compiler hoisting
.
But the declaration is only moved to the top of the function do_something
, not the program
So, Output will beundefined
The Javascript compiler will move the function definition before the variable declaration. Example 8:
According to the above definition, the output will beMoney
Functions declared later, if they have the same name, will overwrite the function declared before
Example 9:
Output will beGem
The Javascript compiler will move the declaration of variables and functions to the top, it is called Hoisting
Only the declaration part is put at the top, not the value assignment part
The function declaration is placed before the variable declaration