DEV Community

Al Moustapha
Al Moustapha

Posted on • Updated on

JAVASCRIPT VARIABLES HOISTING

Hoisting is a fundamental concept in JavaScript that can sometimes confuse developers, especially those new to the language. This article explores this phenomenon in detail, explaining what hoisting is, how it works, and how it affects the scope of variables in your JavaScript programs.

SUMMARY

1. Introduction
2. Definition
3. Hoisting variables with `var` 
4. Hoisting variables with `LET` & `CONST` and classes
5. Temporal dead zone(TDZ)
6. The Hoisting of FUNCTIONS
7. Conclusion
Enter fullscreen mode Exit fullscreen mode

Introduction

For those who are already familiar with JavaScript, it should not be difficult to understand the execution output of this code.

var name = "John";
function displayMessage(params){
   console.log ("Hello slayers");
}

console. Log (name); // John
displayMessage() // Hello slayers
Enter fullscreen mode Exit fullscreen mode

For the next example, I tried a little sleight of hand: accessing a variable and a function before even declaring them. 😁 (Why this audacity, you ask? πŸ˜•) Because I can, of course! 😈 Surprise, surprise... despite this boldness, our function remains perfectly accessible, but the variable plays hide-and-seek.

console.log(name); // undefined
displayMessage() // Hello slayers

var name = "John";
function displayMessage (params) {
console. log( "Hello slayers");
}
Enter fullscreen mode Exit fullscreen mode

Let's take a closer look...

Here, when executing console.log(name), you are greeted by a mysterious undefined, while displayMessage() triggers an enthusiastic Hello slayers.

You might be wondering how this is possible? πŸ‘€ Get ready to be dazzled by the magic of Hoisting! 🀯

Definition

We more or less know what hoisting is. Let's try to get a more formal definition.

In JavaScript, the term "hoisting" refers to the process by which declarations of functions, variables (using var, let, const), or classes are moved to the top of their scope before code execution takes place.
(cf ➜ MDN)

In JavaScript, scope determines where variables and functions are accessible within your code. This definition suffices for our current understanding, but we will explore the topic in greater depth in a future article.

Hoisting variables with var

When you declare a variable with var, the declaration (but not the value assignment) is moved to the top of its context. This means that the variable exists throughout that context, but it is initialized with undefined and only receives its assigned value at the point in the code where the assignment is made.

console.log(name); // undefined
var name = "John";
console.log (name); // John
Enter fullscreen mode Exit fullscreen mode

Hoisting variables with let & const and classes

Hoisting for variables declared with let and const, as well as class declarations, differs from that of declarations with var. Although declarations with let, const, and classes are technically hoisted to the top of their scope, they are not initialized. This creates a temporal dead zone (TDZ) where the variables exist but cannot be used.

console.log(a); // ReferenceError: Cannot access 'a' before initialization
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let a = 3;
const b = 4;
const p = new Rectangle(); // ReferenceError
class Rectangle {}
Enter fullscreen mode Exit fullscreen mode

Temporal dead zone(TDZ)

The Temporal Dead Zone (TDZ) is a period during which a variable declared with let or const, or a class in JavaScript, cannot be accessed or used. The TDZ begins at the start of the block of code where the variable or class is declared and ends at the point where the variable is initialized. Attempting to access a variable in its TDZ results in a ReferenceError, thus preventing the use of uninitialized values.

The Hoisting of FUNCTIONS

Function declarations are fully hoisted. This means that the complete definition of the function, including the body of the function, is moved to the top of its scope. Therefore, you can call a function before it has been declared in the code:

console.log(displayMessage()); // Display "Hello Slayers 🀺!"
function displayMessage() {
return "Hello Slayers 🀺!";
4 }
Enter fullscreen mode Exit fullscreen mode

But...

Function expressions, on the other hand, follow the hoisting rules of variables. If a function expression is assigned to a variable declared with var, the variable's declaration (but not the function expression) is hoisted. Therefore, the variable exists from the beginning of the code execution but is not initialized until the line of assignment:


console.log(sayHello); // Display "undefined"
var sayHello = function displayMessage () {
    return "Hello Slayers βš”οΈ!";
}

console.log(sayHello()); // Display "Hello Slayers βš”οΈ!"
Enter fullscreen mode Exit fullscreen mode

However...

Conclusion

Hoisting is, for many developers, an unknown or overlooked behavior of JavaScript. If a developer does not understand hoisting, their programs may contain bugs (errors). To avoid bugs, it is always advisable to declare all variables at the beginning of each scope. Since this is how JavaScript interprets the code, it's a good rule to follow.

Top comments (0)