DEAL20% OFF
Pre Black FridaySALE
--
Days
--
Hours
--
Minutes
--
Seconds
Book a call
DEAL20% OFF
Pre Black FridaySALE
--
Days
--
Hours
--
Minutes
--
Seconds
Book a call
GLITCH40% OFF
Price Glitch40% OFF
00
Days
00
Hours
05
Minutes
00
Seconds
Claim 40% Off
GLITCH40% OFF
Price Glitch40% OFF
00
Days
00
Hours
05
Minutes
00
Seconds
Claim 40% Off
All articles

JavaScript Hoisting [Explained]

Metana Editorial 4 min read
JavaScript Hoisting [Explained]

JavaScript hoisting is one of those concepts that confuses developers—especially beginners. Many assume that JavaScript moves declarations to the top, but the reality is a bit more nuanced. If not understood correctly, hoisting can lead to unexpected errors and hard-to-debug issues.

In this article, we will break down hoisting, explain how variables and functions behave, highlight common mistakes, and provide best practices to avoid pitfalls.

What is Hoisting in JavaScript?

Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope before execution.

This means you can use variables and functions before declaring them in your code but with some important caveats.

Example of Hoisting:

console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5

You might expect the first console.log(x); to throw an error because x is declared after it, but JavaScript hoists the declaration of x to the top:

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

While declarations are hoisted, assignments are not.

How Javascript Hoisting Works with Variables

JavaScript Hoisting in 2025

var Hoisting

Variables declared with var are hoisted to the top of their function or global scope but are initialized with undefined.

Example:

console.log(name); // Output: undefined
var name = "John";
console.log(name); // Output: "John"

Behind the scenes, JavaScript rearranges the code like this:

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

let and const Hoisting (Why They Are Different)

Variables declared with let and const are hoisted but do not get initialized. This results in a "Temporal Dead Zone" (TDZ) error if accessed before declaration.

Example:

console.log(age); // ReferenceError: Cannot access 'age' before initialization
let age = 30;

In contrast to var, JavaScript does not initialize let and const variables with undefined. Instead, they are in a temporal dead zone from the start of the block until the declaration is encountered.

const Hoisting Rules

const behaves like let but must be assigned a value at declaration:

console.log(pi); // ReferenceError
const pi = 3.14;

How Hoisting Works with Functions

Function Declarations are Fully Hoisted

Unlike variables, function declarations are hoisted with their full implementation.

Example:

greet(); // Output: "Hello, world!"

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

Behind the scenes:

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

greet(); // "Hello, world!"

This means you can call function declarations before defining them.

Function Expressions Are NOT Hoisted

A function expression assigned to a variable behaves differently because only the variable declaration is hoisted, not the function itself.

Example:

sayHi(); // TypeError: sayHi is not a function

var sayHi = function() {
    console.log("Hi!");
};

What happens behind the scenes:

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

Common Mistakes Due to Hoisting

Hoisting can lead to unexpected errors if not handled properly.

Mistake 1: Using var Before Assignment

console.log(user); // undefined
var user = "Alice";
console.log(user); // Alice

Best Practice: Always declare variables before using them.

Mistake 2: Assuming let and const Behave Like var

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

Best Practice: Use let and const to avoid unexpected hoisting issues.

Mistake 3: Using Function Expressions Before Initialization

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

Best Practice: Use function declarations if you need to call them before definition.

Best Practices for Avoiding Hoisting Issues

Declare Variables at the Top of Their Scope

function example() {
    let name;
    console.log(name); // undefined
    name = "Alice";
}

Use const and let Instead of var

let age = 25;
const PI = 3.14;

Use Function Declarations When Possible

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

Avoid Function Expressions Before Declaration

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

Ready to turn this into a career? Metana's software engineering bootcamp is built for beginners and career switchers, with live mentoring, real projects and a job guarantee.

FAQs

What is hoisting in JavaScript?

Are let and const hoisted?

  • Yes, but they remain in the Temporal Dead Zone (TDZ) until their declaration is reached.

What is the difference between function declarations and function expressions in hoisting?

  • Function declarations are hoisted completely.
  • Function expressions are not hoisted (only their variable declaration is hoisted).

How do I avoid hoisting issues?

  • Declare variables at the top.
  • Use let and const.
  • Use function declarations when needed before execution.
Share
TopicsWeb3.0
Metana Editorial

Written by

Metana Editorial

Powered by Metana Editorial Team, our content explores technology, education and innovation. As a team, we strive to provide everything from step-by-step guides to thought provoking insights, so that our readers can gain impeccable knowledge on emerging trends and new skills to confidently build their career. While our articles cover a variety of topics, we are highly focused on Web3, Blockchain, Solidity, Full stack, AI and Cybersecurity. These articles are written, reviewed and thoroughly vetted by our team of subject matter experts, instructors and career coaches.

You may also like

Blockchain

5 Web3 Courses to Try in Coursera

Web3 coursera courses can help you have an opportunity into the web3 industry. As blockchain technology gains popularity, there is a greater need for qualified web3 solidity developers. As we enter the new era of Web3,…

Metana EditorialMay 24, 2023Read
Blockchain

Solidity Developer Job Description: Responsibilities, Salary & Requirements

Blockchain technology has changed the way we do transactions because it's secure, can't be changed, and is transparent. Solidity is a programming language that was made for blockchain. With more and more apps being…

Metana EditorialMay 25, 2023Read
Blockchain

Ethereum Sidechains vs Layer 2 Solutions: Find the Differences

Ethereum has revolutionized the blockchain industry by creating dApps, DeFi, and NFTs. Despite these advancements, scalability issues have led to congestion, high gas fees, and slower transaction times. The community is…

Metana EditorialAugust 23, 2024Read
Blockchain

Step by Step: How To Start Learning Web3

TL;DR Step Description 1 Follow top Web3 builders on Twitter to stay updated 2 Learn via video tutorials on YouTube 3 Build simple projects like ERC‑20 tokens or smart contracts 4 Join a bootcamp if you want structured…

Kavinesh GaneshamoorthyAugust 1, 2025Read
Blockchain

Exploring the Mempool: A Deep Dive

Have you ever sent a cryptocurrency payment and felt like it's taking forever to confirm? You're not alone. Unlike swiping your debit card, crypto transactions don't happen instantaneously. There's a waiting room for…

Metana EditorialJune 18, 2024Read
Blockchain

Solidity and Homomorphic Encryption: The Key to Confidential Smart Contracts

Blockchain tech is a hive of activity, buzzing with ideas to make it safer and more private for everyone. Two prominent players in this arena are Solidity, the backbone of smart contracts, and homomorphic encryption, a…

Metana EditorialJuly 7, 2025Read
More Blockchain articles →

Talk to an advisor

Book a call with a real human before the next cohort fills.

Speak with an advisor. We'll map the right program to your goals - and lock in your enrollment offer.

20% off enrollment offer

20% OFF - limited-time enrollment offer.

Applied automatically when you book a call before the timer hits zero.

--
Days
--
Hours
--
Minutes
--
Seconds
  • Guarantee: Job or 100% money back
  • Expert-curated curriculum
  • On-demand mentor support
Advisor Elena RodriguezAdvisor Sarah JenningsAdvisor David Chen
Real advisors · reply within 2 hours

Book your call

Free