Introduction to Hoisting in JavaScript
Table of contents
The JavaScript engine or interpreter when reading the script takes the variable declaration and function declaration to the top in memory, Initialisations are not hoisted.
๐ฉโ๐ป Coding Time
Example - 1
console.log(a)
// var is hoisted means we can access it before the initialization
// but its value will be undefined as it's not assigned any value.
var a = 10
// let and const are not hoisted, means we can't access them above
// let a = 10
// const a = 10
// we can access greet over here as it is hoisted.
greet()
// we cannot access hello as it is a arrow function.
// hello()
// here the function is declared hence it's hoisted.
function greet() {
console.log("hello world")
}
// Here we are initialising hello with an anonymous function meaning without
// function keyword hence it's also not hoisted.
// In short: the arrow function is not hoisted.
const hello = ()=>{
console.log("hello world")
}
If you've grasped the concept in the first example, you've effectively understood hoisting. However, in the below example, behaviour differs from the standard hoisting, so please remain clear to avoid any confusion.
Example - 2
const initApp = ()=>{
console.log(hello)
/*
hello function will be initialized before calling initApp hence
below code will be printed for the above line
() => {
console.log("hello world")
}
*/
hello()
}
// here we will not get initialization error for hello although we are trying to access
// it before initialization in initApp function because while listening to
// DOMContentLoaded event javascript doesn't call initApp function directly it first
// initializes all the function inside initApp and then it calls it.
document.addEventListener("DOMContentLoaded",initApp)
// here we are initialising hello with a anonymous function means without
// function keyword hence it's also not hoisted.
// In short: arrow function is not hoisted.
const hello = ()=>{
console.log("hello world")
}
Conclusion
Hoisting: While interpreting the scripts JavaScript engine puts some code at the top in memory.
var variables and function declared using function keyword is hoisted.
let and const are not hoisted and the arrow function is also not hoisted.
Subscribe to my newsletter
Read articles from vishal singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
vishal singh
vishal singh
My name is Vishal Singh, and I am currently pursuing my B.Tech degree from Future Institute of Engineering and Management. I am also a web developer with experience in HTML, CSS, JS, Node js, Express js MongoDB and others. I am passionate about creating high-quality and user-friendly websites that provide value to their users.