Hoisting
Table of contents
👉 Hoisting is the process in which interpreter moves all the declaration to the top of the scope before execution.
This means that we can access functions, variables before they have been declared in the source code.
In JavaScript Variable declrattion, initialization and usage has a fixed sequence
Declaration→Initialization/assignment→Usage
Function Hoisting
Functions are also hoisted in JS, therefore we can access functions before there declarations.
Example:
foo()
function foo(){
console.log('Hello World')
}
The above snippet will give output : Hello World
Variable Hoisting
Variable var, let, const are also hoisted in JS therefore we can use them too before declaring them.
Only declarations are hoisted in JS and not initialization, declaration of variables happen at memory allocation phase in JS and initialization of variables happen at the time of code execution.
That means whatever value we have initialized our variables with that value will only be assigned to the variable whent the code execution reached that line of code, untill then a default value is assigned to the variables.
👉 Default value is undefined if the variable is declared using var , else it is uninitialized.
Examples of using variables before there initialization are discussed below.
Hoisting var
Variables declared using var keywords are hoisted and we can access them before initialization, it’s default value will be undefined.
console.log(name)
var name ="sudhanshu soni"
The code snippet above will give output: undefined
Hoisting let and const
Variables declared using let and const are hoisted but they are not assigned with any default value, if you try to access them before initialization it wil give you an reference error quoting “cannot access variable before initialization”
console.log(name)
let name = "sudhanshu soni"
console.log(name)
const name = "sudhanshu soni"
Both of the code snippets above will throw a reference error.