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 Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay