Hoisting in JavaScript means that any declaration made, JavaScript will move them to the top of their scope before the code runs.
๐ฆ Two types of Hoisting in JavaScript
- Variable Hoisting :
Lets see using examples:
console.log(x); //undefined
var x = 8;
console.log(x); //prints 8
Instead of throwing an error it runs as x
is hoisted to the top of the scope therefore its not initialized before the code runs but its declared therefore x
is accessible. x
is initialized when the line var x = 8
is executed.
NOW lets see using let
and const
:
console.log(x); //ReferenceError: Cannot access 'x' before initialization
let x = 8;
console.log(x); //does not reach because of error
let
and const
are also hoisted but they cannot be accessed before initialization, hence throwing a reference Error !
Initialization happens when the declaration line like let x = 8;
is reached, if nothing is initialized its undefined
!
Same case with const
!
- Function Hoisting:
Functions are also hoisted by default ! Lets see:
hello(); // โ
This runs
function hello(){
console.log("Hello Brother !");
}
but if used using const
it will follow the hoisting rules applied to const
and let
hello(); // โ ReferenceError: Cannot access 'hello' before initialization
const hello = () => console.log("Hello Brother !");
hello is a const
value here therefore cannot access it before initialization !
FINAL THOUGHTS
THAT WAS HOISITNG IN JS ! And yes peculiar quirky codes can be done using this (maybe).
Check Quirky JavaScript Here : Quirky JavaScript