Hoisting in JS

Hoisting in JS

Learn about hoisting and how it works.

In this blog, we will be talking about Hoisting in JavaScript, how it works and what does it mean to hoist a variable. Before starting, we should know what the word 'hoist' means:

Hoist means to raise up something like hoisting of flag.

In context to JavaScript, Hoisting means to raise up the declaration of the variable with respect to the current scope. It is a default feature of JavaScript prior to ES2015. Hoisting enables to use a variable before declaring it.

var fruitName; 
fruitName = "Apple";
console.log(fruitName) //Apple

or

fruitName = "Apple";
console.log(fruitName);  // Apple
var fruitName;

In both of the above examples, we get output as "Apple" but a point to note here is that only the declaration of the variable is hoisted not the initialization.

console.log(fruitName);  // undefined
var fruitName;
fruitName = "Apple";

It is taken by the compiler in the following order:

var fruitName;
console.log(fruitName);  // undefined
fruitName = "Apple";

Replacing var with let and const

Hoisting with let and const is similar to var. In let and const, the variables are also hoisted at the top just with a slight difference that they are not initialized.

fruitName = "Apple";
let fruitName;
console.log(fruitName);  // Reference Error: Cannot access 'fruitName' before initialization

Similar in const:

fruitName = "Apple";
const fruitName;
console.log(fruitName);  // SyntaxError: Missing initializer in const declaration

Summary

  • Hoisting means raising up the declarations of variables.
  • Only the declarations are hoisted not the initialization.
  • Hoisting works in same way with different data types like integer, floating numbers, etc.
  • var, let and const are similar in hoisting but let and const are not initialized