JavaScript Interview Question #8
What is hoisting in JavaScript?
JavaScript Fundamentals, Types, Scope & Functions Junior Beginner
Quick Interview Answer
Hoisting describes how JavaScript processes declarations before executing code in a scope. Function declarations can generally be called before their textual declaration. var declarations are hoisted and initialized with undefined.
Detailed Explanation
Hoisting describes how JavaScript processes declarations before executing code in a scope. Function declarations can generally be called before their textual declaration. var declarations are hoisted and initialized with undefined.
let, const, and class declarations are also associated with their scope before execution, but they remain inaccessible until their declaration is evaluated. Accessing them during this period causes a ReferenceError because of the temporal dead zone.
Code Example
sayHello(); // Works
function sayHello() {
console.log("Hello");
}
console.log(value); // undefined
var value = 10;
// console.log(count); // ReferenceError
let count = 5;