DEV Community

Cover image for Hoisting
Deepdil
Deepdil

Posted on

1 1 1

Hoisting

What is Hoisting?

Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their containing scope during the compilation phase, regardless of where they are declared in the code.

Variable Hoisting:
Consider the following code snippet:
console.log(x); // undefined
var x = 10;

Surprisingly, this code doesn't throw a reference error. Instead, it logs 'undefined'. This is because, during compilation, JavaScript moves the variable declaration var x to the top of its scope. Essentially, the code above behaves like this:
var x;
console.log(x); // undefined
x = 10;

Function Hoisting:
Similar to variables, function declarations are also hoisted. Let's examine another example:
foo(); // "Hello, world!"
function foo() {
console.log("Hello, world!");
}

Even though foo() is invoked before its declaration, JavaScript doesn't complain. This is because the function declaration function foo() is hoisted to the top of its containing scope, allowing it to be invoked anywhere within that scope.

Hoisting in ES6:

With the introduction of ES6 (ECMAScript 2015), let and const were introduced as block-scoped alternatives to var. While let and const are still hoisted, they're not initialized until their actual declaration in the code. This is known as the "Temporal Dead Zone". In Interviews the term TDZ is always pointed to explain. so understand the term is also important.
console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 10;

Best Practices:

  • Declare variables and functions at the top of their scope to improve code readability and avoid unexpected behavior due to hoisting.

  • Prefer let and const over var for better block scoping and to minimize hoisting-related issues.

  • Use strict mode ('use strict';) to catch undeclared variables and other common mistakes.

Image of Bright Data

Feed Your Models Real-Time Data – Enhance your AI with up-to-the-minute data.

Utilize our live data feeds for dynamic model training, ensuring your AI systems are always ahead.

Access Real-Time Data

Top comments (0)

Billboard image

Use Playwright to test. Use Playwright to monitor.

Join Vercel, CrowdStrike, and thousands of other teams that run end-to-end monitors on Checkly's programmable monitoring platform.

Get started now!

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay