If you are finding hoisting confusing, here is an article to help you understand hoisting better.
According to the definition of hoisting, the Java Script engine excutes divides into two phases, one is to initialize variables and functions, the other is to assign values to variables and functions.
Hoisting
refers to the process whereby the interpreter allocates memory variable and
function declarations prior to execute the code.
And hoisting
occurs when variables or functions are called before being initialized. And
when the JavaScript engine executes it puts the initialization variables and
functions first.
Look at the example below with var when initialized variable:
Try to guess
what the outcome will be?
This means that when initializing the engine variable Java Script initializes the variable first and assigns it the value undefined before executing console.log().
It would be like something like this:
So let's try
to initialize with let(const) and do the same thing as above:
And again,
guess what will happen?
If your
guess is wrong then you have a correct answer, if not, that's okay because I'll
show you where the difference lies:
The above
let(const) initialization would be similar to something like this:
But the interesting thing is that when initialized with let(const), the variable will be put into the "tempotal dead zone", simply understood that this variable will not be able to be used without being assigned a value. Besides, it also means not assigning undefined as var.
Let's try with initialized function will be like?
And guess
what the outcome will be?
Wow! It's
interesting. So what's the difference between the function and the above?
One of the
advantages of JavaScript putting function declarations into memory before it
executes any code segment is that it allows you to use a function before you
declare it in your code.<< Developer Mozilla >>
It means
that you would execute the function above like this:
Let's do
some examples to better understand hoisting:
Example 1:
Example 2:
Example 3:
In the
example 1:
y is
hoisting and has a value is undefine, x = 1. The result is 1 + undefined, but
in the engine Java Script this mean NaN (Not a number).
In the
example 2:
y is
hoisting but y in the temperal death zone, can not access y. Finally, result is
In the
example 3:
x and y are hoisting and be in the temperal death zone can not access x and y. And result is error.
Thank you
for joining us through all the articles on hoisting. Feel free to comment
below! Thank you and have a good day!
3 Nhận xét
good job em
Trả lờiXóatuyệt vời lắm em
Trả lờiXóabổ ích quá ạ. em đang vướng cái này luôn
Trả lờiXóa