Skip to main content

Command Palette

Search for a command to run...

15. MEDIUM | Hoisting in Javascript

This article will talk about hoisting in javascript.

Updated
•2 min read•View as Markdown
S
Full-Stack Developer with 4 years' experience, specializing in backend development. Skilled in JavaScript, React, Python, Databases, and AWS. Known for building scalable web apps, leading teams, and maintaining strong client communication. Upskilling in Generative AI.

What is Hoisting?

Hoisting refers to the process whereby the interpreter appears to move var variables, function declarations and class declarations to the top of the code before execution.

var variables, function declarations and class declarations can thus be referenced before they are declared in javascript.

console.log(username); // Output: undefined

sayHi(); // Output: Hi, Shubham!

var username = 'shubham';

function sayHi() {
    console.log("Hi, Shubham!")
}
💡
let and const variables, function expressions and class expressions are not hoisted. If we try to refer them before initialization, we will get ReferenceError.
// let and const variables

console.log(username); // throws ReferenceError [Reason:- let in TDZ]
console.log(age); // throws ReferenceError [Reason:- const in TDZ]

let username = 'shubham';
const age = 25;
// function expressions

func1(); // Error [Reason:- undefined()]
func2(); // Error [Reason:- let in TDZ]
func3(); // Error [Reason:- const in TDZ]

var func1 = function() {
    console.log('I am func1.')
};

let func2 = function() {
    console.log('I am func2.')
};

const func3 = function() {
    console.log('I am func3.')
};

Logic behind hoisting behaviors?

Javascript code is executed in 2 phases viz. first, memory creation phase and second, code execution phase.


Happy reading!