JavaScript Hoisting

In JavaScript, hoisting refers to a fundamental behavior that enables the declarations of functions, variables, and classes to be elevated to the top of their respective scopes prior to the execution of the code.

In straightforward terms, hoisting refers to the mechanism that elevates the declarations of variables and functions to the beginning of their designated scopes. This behavior guarantees that regardless of their position within a scope, these declarations remain accessible throughout the entire scope.

Example

Example

console.log(a);

var a = 10;

Output:

Output

undefined

Explanation

In this snippet, the declaration of variable var a is elevated to the beginning of its scope, yet a is assigned a value of undefined. Consequently, the result produced by the code will be undefined.

Why do we use JavaScript hoisting?

There are several motivations for utilizing JavaScript hoisting:

Ease of use

In JavaScript, the concept of hoisting enables programmers to invoke functions prior to their declaration within the code, thereby enhancing the readability and intuitiveness of the code. For instance, we are able to call a function even before it appears in the source code.

Function declaration scope

In JavaScript, function declarations undergo a complete hoisting process, signifying that both the name of the function and its body are elevated to the top of the scope. This feature enables you to declare functions at any point within your code while still being able to invoke them from any location within the same scope.

Variable declaration

It is indeed hoisted, albeit with a nuanced distinction. The only aspect that is elevated to the top of the scope is the variable name, while the actual assignment retains its original position. This can occasionally result in unforeseen behavior if not fully comprehended.

Execution order

Grasping the concept of hoisting enables us, as programmers, to anticipate the sequence in which variables and functions are executed, thereby helping to avoid errors and unintended behavior within the code.

Avoiding reference errors

In JavaScript, the concept of hoisting enables us to prevent reference errors that could arise from utilizing variables or functions prior to their declaration. Unlike many other programming languages, where referencing a variable before it has been declared can lead to an error, JavaScript's hoisting feature permits the code to operate correctly despite this situation.

Temporal Dead Zone(TDZ)

In JavaScript, the concept of the temporal dead zone (TDZ) plays a crucial role in understanding hoisting. This term refers to a timeframe during the execution of code in which variables declared using let and const are indeed hoisted into memory, yet remain inaccessible.

In basic terms, you are unable to utilize these variables prior to their declaration within the code, despite the fact that they are theoretically accessible in the scope because of hoisting. If you try to refer to the variable before it has been initialized, a ReferenceError will be raised.

Example

Example

console.log(a); // ReferenceError: Cannot access 'a' before initialization

let a = 5;

console.log(a); // Output: 5

Output:

Output

ReferenceError: Cannot access 'a' before initialization

Types of Hoisting

Variable Hoisting

The manner in which hoisting operates in JavaScript is contingent on the method of variable declaration, specifically whether a variable is declared with var, let, or const.

Hoisting with var

In JavaScript, declaring a variable with the var keyword results in the variable being hoisted to the beginning of its existing scope.

Example

Example

console.log(a);

var a = 10;

Output:

Output

undefined

Explanation

In the code provided, it is possible to utilize the variable a prior to its declaration. This occurs due to the concept of hoisting, which allows the variable to be elevated in the execution context with an initial value of undefined.

Hoisting with let and const

In JavaScript, when a variable is defined with the let and const keywords, it gets hoisted to the beginning of its respective scope. Nonetheless, the hoisted variable does not possess an initial value at the time of hoisting.

Example

Example

// use the demo variable before declaration

console.log(demo);

// variable declaration using let keyword

let demo;

Output:

Output

ReferenceError: Cannot access `demo` before initialization

Explanation

In this code snippet, an error arises due to the fact that a variable defined using let does not receive any initial value during the hoisting process.

Function Hoisting

In JavaScript, function hoisting refers to a mechanism that allows a function to be invoked prior to its actual declaration in the code.

Example

Example

console.log(demo()); 

function demo() {

 return "Hello, Denji!";

}

Output:

Output

Hello, Denji!

Explanation

In this code snippet, we are able to invoke demo prior to its declaration due to the concept of hoisting.

Class Hoisting

In JavaScript, classes undergo hoisting; however, they cannot be utilized prior to their declaration since they exist in the Temporal Dead Zone until the declaration is processed.

Example

Example

const myInstance = new MyClass(); // ReferenceError

class MyClass {

  constructor() {

    console.log("Instance created");

  }

}

Output:

Output

ReferenceError: Cannot access 'MyClass' before initialization

Features of JavaScript Hoisting

JavaScript hoisting comes with several important characteristics, including:

Variable Declarations

In JavaScript, variables that are declared using the var keyword experience hoisting to the pinnacle of their respective scope. Nevertheless, only the declaration itself is hoisted, while the initialization remains unaffected. This implies that a variable can be referenced prior to its declaration; however, its value will remain undefined until it has been assigned an actual value.

Example

console.log(MyVar);  

var myVar = 10;

Function declaration

In JavaScript, function declarations undergo complete hoisting, which encompasses both the name of the function and its corresponding implementation. This characteristic enables you to invoke a function prior to its declaration within the code.

Example

myFunction();  

function myFunction() {  

console.log("Hello!");  

}

Function expression

In JavaScript, a function expression refers to the scenario in which functions are assigned to variables, and these variables do not undergo hoisting in the same manner as function declarations do. In this case, only the declaration of the variable is hoisted, while the assignment of the function remains unhoisted.

Example

myFunction(); // Error: myFunction is not a function  

var myFunction = function() {  

    console.log("Hello!");  

};

Block Scoping

In JavaScript, variables that are defined using let and const are hoisted to the beginning of their respective block scope; however, in contrast to var, these variables remain uninitialized until the moment their declaration is executed. This phenomenon is referred to as the "temporal dead zone."

Example

console.log(myVar); // ReferenceError: Cannot access 'myVar' before initialization  

let myVar = 10;

Conclusion

In JavaScript, hoisting is a crucial concept that elevates variable and function declarations to the beginning of their respective scope during the compilation stage. This behavior enables the use of variables and functions prior to their explicit declarations within the code.

Input Required

This code uses input(). Please provide values below: