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 var…


This content originally appeared on DEV Community and was authored by Al Moustapha

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.

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

For this 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");
}

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)

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

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 {}

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 }

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 ⚔️!"

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.


This content originally appeared on DEV Community and was authored by Al Moustapha


Print Share Comment Cite Upload Translate Updates
APA

Al Moustapha | Sciencx (2024-07-21T02:29:05+00:00) JAVASCRIPT VARIABLES HOISTING. Retrieved from https://www.scien.cx/2024/07/21/javascript-variables-hoisting/

MLA
" » JAVASCRIPT VARIABLES HOISTING." Al Moustapha | Sciencx - Sunday July 21, 2024, https://www.scien.cx/2024/07/21/javascript-variables-hoisting/
HARVARD
Al Moustapha | Sciencx Sunday July 21, 2024 » JAVASCRIPT VARIABLES HOISTING., viewed ,<https://www.scien.cx/2024/07/21/javascript-variables-hoisting/>
VANCOUVER
Al Moustapha | Sciencx - » JAVASCRIPT VARIABLES HOISTING. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/21/javascript-variables-hoisting/
CHICAGO
" » JAVASCRIPT VARIABLES HOISTING." Al Moustapha | Sciencx - Accessed . https://www.scien.cx/2024/07/21/javascript-variables-hoisting/
IEEE
" » JAVASCRIPT VARIABLES HOISTING." Al Moustapha | Sciencx [Online]. Available: https://www.scien.cx/2024/07/21/javascript-variables-hoisting/. [Accessed: ]
rf:citation
» JAVASCRIPT VARIABLES HOISTING | Al Moustapha | Sciencx | https://www.scien.cx/2024/07/21/javascript-variables-hoisting/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.