Introduction
JavaScript file when runs it actually completes in two steps . One is scanning the file from top to bottom and other is execution step. In scanning step , js reads all variables and initialise undefined to them and read functions declarations. Memory allocation is given to variables and functions. In execution step, variable initialisation happens and function execution also happens.
What is Hoisting in JavaScript?
Hoisting topic appears in scanning step. Hoisting is a process where interpreter moves all variable and function declarations on to top of their scope before execution.
Function Hoisting
Because of hoisting only functions can be called before they are declared. This is because in scanning step js has allocated memory for function.This is same for classes
also.
Example for Function Hoisting:
greet() // function is being called before declaration
function greet(){
console.log("Hiii")
}
//output : Hiii
Variable Hoisting
var
hoisting.
While scanning var
variables are allocated memory with undefined value in global scope.
var variables can be accessed before initialisation.
console.log(a); // output : undefined
var a; // declaration (hoisted)
a = 10;
console.log(a); // output : 10
let
const
hoisting.
unlike var
, let
and const
are hoisted in different way. They are not initialised with undefined or default value. let
and const
are allocated memory in a different scope. they can't be accessed with out initialisation.
console.log(a); // reference error
let a =10;
let b ;
console.log(b); // reference error
// let variable should be initialised
b=10;