Introduction to Hoisting in JavaScript

Introduction to Hoisting in JavaScript

ยท

2 min read

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.

ย