Let's discuss the concept of Hoisting in JavaScript, which is one of the key topics that frequently appears in top JavaScript interview questions.
Category
JavaScript
Javascript interview
Interview
Hoisting
Cover
Slug
javascript-hoisting
Date
‣
author
Published
Published
Hello friends,
Today, we’ll be exploring another important topic, the concept of Hoisting in JavaScript.
Hoisting in JavaScript:
This refers to the process of "lifting" variable (var, let, const) and function declarations to the top of their scope before code execution. This means that declarations are moved to the top during compilation, allowing you to use variables or functions before they are declared in the code.
Due to hoisting in JavaScript, you can use variables before they are declared, but if they are not initialized before usage, they will have a value of undefined.
Example:
console.log(x); // undefined
var x = 5;
console.log(x); // 5
In the code above, the declaration of var x is hoisted to the top, but the assignment remains in place. That's why the first console.log(x) outputs undefined.
Understanding Hoisting
The above example is interpreted as follows:
var x;
console.log(x); // undefined
x = 5;
console.log(x); // 5
Hoisting with Functions
Function declarations are also subject to hoisting. This means you can call functions even before they are declared.
sayHello(); // "Hello, world!"
function sayHello() {
console.log("Hello, world!");
}
In this code, the sayHello function is hoisted to the top, so you can call it before its declaration.
Hoisting with Let and Const
Variables declared with let and const are also hoisted, but they are placed in a "Temporal Dead Zone" (TDZ). This means that while the declaration is hoisted, the variable cannot be accessed until it is initialized, resulting in an error if you try to use it too early.
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 10;
In this case, the y variable is hoisted but remains in the TDZ, causing an error when accessed before initialization.
Conclusion: Hoisting is a fundamental feature of JavaScript that moves declarations to the top of the code. Understanding this behavior is essential for writing clear and error-free code.