Hoisting
JavaScript Hoisting refers to the process where the interpreter allocates memory for variables and function declarations prior to the execution of the code.
Declarations that are made using the var keyword are initialized with the default value of undefined
Declarations made using the let and the const keywords are not initialized as a part of the hoisting
Hoisting takes place during the creation phase of the Execution Context.
consider the following script:
Steps involved in the execution of the above script:
- A new Global Execution Context is created.
- num variable is initialized with undefined.
- In the execution phase, the code is executed line-by-line.
- In the first line it logs undefined to the console.
- Line two is skipped as it already defined num in the creation phase.
- In line three a value of 6 is assigned to num.
let and const keywords
let and const keywords are hoisted but not initialized
Consider the following script:
What happened in the above script, as the let is not initialized with any value it throws a reference error.
Temporal Dead Zone
let and const are hoisted and initialized with undefined. But as they reside in a special memory location called Temporal Dead Zone, they cannot be referenced until and unless they are initialized.
Function Hoisting
Normal Functions
Normal functions are fully defined in the context creation phase and referenced to Function Execution Context.
Normal functions are always fully hoisted.
Function Expressions
Functions in JavaScript are first-class citizens. They are treated just similarly to any other variable or data type.
Consider the following scripts:
output: 7
TypeError: y is not a function
In the second example, at the creation phase, the JS engine sees y as a variable and initializes it with undefined. In the creation phase, it doesn't know it is a function.
Comments
Post a Comment