Img Credit : Vitolda Klein
Introduction
When you load your javascript to browser, javascript engine executes it and create global execution context. That has two phases.
- Creation
- Execution
Hosting happens on when the phase on creation mode, the javascript engine moves the Variable and Function declaration to the top of the scope.
Variable Hoisting
Lets run the Example : 1 code first.
Example : 1
Hope it doesn't make an error and showing "undefined". Cause Javascript moves the Variable declaration top of the scope.
okay, just run Example : 2 code
Example : 2
I think , still you got the same result on example two.
Its meaning during the creation phase, var name automatically declare to the top & initialize value "undefined"
Function Hoisting
Lets run the Example : 1 code first.
Example : 1
Like as Variable Javascript engine hoisted the function to the top.
Example : 2
If you compare the output both are giving same result. During the creating phase the function add automatically move to the top of scope.
Note :
- Unlike var, they are not initialized with a default value while hoisting.
- They cannot be read/written until they have been fully initialized.
- Javscript hoisting not working arrow function and expression.
If there has any issues or wrong instruction, please feel free to contact with me by comments or mail: hello@rathik.dev