TechnicalEasy JavaScript
What is hoisting in JavaScript?
Asked for Frontend Developer, Full-Stack Developer
Why they ask this: A classic fundamentals check that also reveals whether you understand let/const and the temporal dead zone.
Answer
Hoisting means declarations are processed before code runs, so they are known in their whole scope.
- Function declarations are hoisted with their body, so you can call them before they appear.
varis hoisted and initialised toundefined.let,constandclassare hoisted too, but stay uninitialised (the temporal dead zone) until the declaration line runs. Accessing them earlier throws aReferenceError.
js
greet(); // works
function greet() { console.log('Namaste'); }
console.log(a); // undefined
var a = 1;
console.log(b); // ReferenceError
let b = 2;Function expressions (const greet = () => {}) follow the rules of the variable they are assigned to.
Can you explain this in your own words?