DEV Community

AshaS22
AshaS22

Posted on

Day 4: Hoisting in JS

Alt Text
Hoisting is the mechanism where the JS interpreter scan the code and hoists the variables and functions at the top so that they can be accessed before declaring them.

Javascript handles hoisting of variables and functions differently.

Variable Hoisting

var

console.log(name) // undefined
var name = "xyz"
console.log(name) // "xyz"

After hoisting, the above code looks like the code snippet written below

var name;
console.log(name) // undefined
name = "xyz"
console.log(name) //

Hence the first line of console.log(name) outputs undefined instead of throwing an error.

let and const
They way hoisting is handled with let and const is different than how var is handled. We wont be able to access the variable until it is declared.

Lets look at the previous example with let keyword

console.log(name) // throws error
let name = "xyz"
console.log(name) // "xyz"

This happens because, in case of var, before executing the code line by line, variables are declared and initialised with undefined. But, let/const doesn't get initialised until it finds the initialisation in the code. So, when we try to access the variable, it throws an error.

Function Hoisting

In JS there are three ways of in which we create function.

  1. Function Declaration
  2. Function Expression
  3. Arrow functions

Function Declaration
Ex of regular function declaration

function addNum(a, b){
return a+b;
}

When the interpreter scans the JS code, regular function definitions are hoisted at the top and made available at all other places

console.log(addNum(4, 5)) //prints 9
function addNum(a, b){
return a+b;
}

Once this code is hoisted it looks as below

//Hoisted function definition
console.log(addNum(4, 5)) //prints 9
...
...
Rest of the code follows

Function Expression

console.log(add(4, 5)) //throws error add is not a function
var add = function (a, b){
return a+b;
}

functions Expressions are not completely hoisted in JS, Instead only declarations are hoisted bcz, it is only recognised as variable.

In the same way, when a function is referenced using let keyword, hoisting behaves the same way as that of regular let.
Ex:

console.log(add(4, 5)) //throws error
let add = function (a, b){
return a+b;
}

Arrow functions

Just like function Expressions, arrow functions are not hoisted in JS

Top comments (1)

Collapse
 
kingleo10 profile image
Niroj Dahal

Nicely explained