What is hoisting in JavaScript?

👨‍💻 Frontend Developer 🟡 Often Asked 🎚️ Medium
#JavaScript #JS Basics #Data types

Definition

Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their scope before code execution.

This doesn’t mean the code is physically moved, but the JavaScript engine processes declarations first, then executes.


How does it work?

Example with var

console.log(a); // undefined
var a = 5;

The variable a is hoisted, but the assignment (= 5) happens later. Internally, it behaves like this:

var a;
console.log(a); // undefined
a = 5;

Example with let and const

console.log(b); // ReferenceError
let b = 10;

let and const are hoisted too, but enter the TDZ (Temporal Dead Zone) — a phase where the variable exists but accessing it throws an error until initialization.


Example with function

greet(); // "Hello!"
 
function greet() {
  console.log("Hello!");
}

Functions declared with function declaration are fully hoisted, including their body.


Example with function expression

sayHi(); // TypeError: sayHi is not a function
 
var sayHi = function() {
  console.log("Hi");
};

sayHi is declared using var, so it’s hoisted as undefined. The function is not yet assigned at call time.


What gets hoisted?

Construct TypeHoisted?Comment
varYesDeclaration is hoisted, but initialization is not
let / constYes (in TDZ)ReferenceError before initialization
function declarationYesFully hoisted with the function body
function expressionPartiallyVariable hoisted as undefined, not the function
arrow function via constYes (in TDZ)ReferenceError before initialization

Practice Tasks

Task 1

console.log(name);
var name = "Aleksandr Ermolov";
Answer `undefined` — variable is hoisted, value is assigned later.

Task 2

sayHello();
 
function sayHello() {
  console.log("Hello");
}
Answer "Hello" — function declaration is fully hoisted.

Task 3

sayBye();
 
var sayBye = function () {
  console.log("Bye");
};
Answer TypeError — `sayBye` is `undefined` at call time.

Task 4

console.log(age);
let age = 30;
Answer ReferenceError — `let` is in TDZ before initialization.

Task 5

greet();
 
const greet = () => {
  console.log("Hi!");
};
Answer ReferenceError — `const` is in TDZ; arrow function is a function expression.

Task 6

if (true) {
  var test = "yes";
}
console.log(test);
Answer "yes" — `var` has function scope, not block scope.

Summary

  • var and function declaration are hoisted, let/const too but live in the TDZ.
  • Function expressions are not hoisted as executable functions.
  • Understanding hoisting helps avoid subtle bugs and ace interviews.

Want more articles on interview preparation?
Follow EasyAdvice, bookmark the site, and level up every day 💪