DEV Community

Cover image for Hoisting
Deepdil
Deepdil

Posted on

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.

Top comments (0)