What is Hoisting in JavaScript?

JS-hoisting

Hoisting in javascript is default behavior of moving declaration to the top of the scope. This behavior some time makes more confusion. However, hoisting can be divided into two part, variable hoisting and function hoisting.

Variable Hoisting

Variable with var keyword always hoist and initialized into undefined. That mean javascript engine allocates necessary memory space with indicating it has no value of undefined.

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

However, let and const variable are still hoisted but can’t access until Initialize.( according the ECMAScript specification). If let available has not value, javascript engine will assign undefined.

console.log(name); //Uncaught ReferenceError: Cannot access 'name' before initialization
let name = "manoj prasad";

This behavior apply for every where in javascript, such as global scope, or even in function scope.

variable = undefined is not recommend in JavaScript, best way to set that, variable = null.

console.log(name); //undefined, this variable has hoisted

var name = 'manoj prasad';
console.log(name); //manoj prasad

//later you want to make no value, you simply put null instead of undefined. That really helps to figure out, it had an initial value or not.
name = null;

Function Hoisting

All function declaration will be hoisted in the scope which is declared, so that function can be called before declaration.

sayHello(); // Hello

function sayHello() {
  console.log('Hello');
}

JavaScript functions are just an object which holding key value pair. I’ll conver this in another post.

Function expression and ES6 arrow function will not be hoisted.

sayHelloFromExpression();  //Uncaught TypeError: sayHelloFromExpression is not a function

var sayHelloFromExpression = function() { 
  console.log('Hello');
}
sayHelloFromArrow();  //Uncaught TypeError: sayHelloFromArrow is not a function

var  sayHelloFromArrow = () => {
  console.log('Hello');
}

Now it’s clear that both variable and function declarations are hoisted in current scope. But which one take precedence.

What takes precedence?

Function declaration will take highest precedence than the variable on hoisting.

console.log(typeof name);
var name = "Manoj Prasad"; 

function name(){
   console.log(name);
}
console.log(typeof name);

function name(){
   console.log(name);
}

var name = "Manoj Prasad"; 

typeof will give function as output even though function has been declared after the variable.

Summarize

In javascript, variable and function declaration will be hoisted. That mean, variable with var can be used before it has been assigned a value or function declaration can be executed. So it’s power of functional programing. Key point is, “To avoid bugs, always declare all variables at the beginning of every scope.”

2 Replies to “What is Hoisting in JavaScript?”

Leave a Reply