codemarch
codemarch

@codemarch

15 Tweets 3 reads Aug 21, 2022
JavaScript Hoisting.
Complete Explanation:
Thread 🧵
Before Starting the concept of Hoisting , you have to understand the flow of “ How JavaScript Works “ .
Hoisting is JavaScript's default behavior of moving declarations to the top.
In JavaScript, a variable can be declared after it has been used.
In other words; a variable can be used before it has been declared.
First, we'll examine the results of calling a function without first defining it.
Here, we define the hello function to ensure that the output is written properly.
We'll use the same example moving forward, except this time we'll call the function before we declare it.
that is the concept of Hoisting because the JavaScript Interpreter will move all declarations to the top of the current scope. ( It means they pull the defination of the function at the top )
Let's examine the same hoisting concept in a variable.
First, we will declare, assign, and then we will call it,
➡️Example:-
In this case, the function was called before Assigning and you got the output ‘undefined’.
Only the declaration is moved to the memory in the compile phase. Hence, the value of variable a
 is "undefined"
When a variable is declared as var, it defaults to assigning undefined.
Internally , It’s like
Because of the concept of hoisting, it won't fail in this scenario (default behaviour of moving declarations to the top)
Here,
The output will be undefined because they only pull the declaration portion and assign it ‘undefined’ by default.
The let and const Keywords
variables defined with "let" and "const"
are hoisted to the top of the block, but not initialized.
If a variable is used with the "let" keyword
They only pull the declaration part but they won't assign it to "undefined" , so it will throw an error.
Using a "let" variable before it is declared will result in a "ReferenceError".
The variable is in a "temporal dead zone" from the start of the block until it is declared:
If you enjoyed reading this thread, please do the following:
1. Like the thread❤️
2. Retweet the first tweet.🔃
3. Follow me and enable notifications: ✅
@CodeMarch
Thank you for reading all the way through.
Download our free JavaScript Resources ebook Here:
codemarch.gumroad.com

Loading suggestions...