Hoisting is JavaScript's behaviour of processing declarations before executing code in a scope. During the creation phase of each execution context, the engine registers variable and function declarations, so they exist (in some form) from the start of their scope — as if they were "moved to the top". The code itself is not physically moved. Function declarations — fully hoisted greet(); // "Hello" — works before the declaration function greet() { console.log('Hello'); } Both the name and the function body are available throughout the scope. var — hoisted and initialised with undefined console.log(total); // undefined (no error) var total = 100; console.log(total); // 100 The declaration is hoisted, but the assignment stays where it is. JavaScript treats it like: var total; console.log(total); total = 100; let and const — hoisted but in the Temporal Dead Zone console.log(price); // ReferenceError: Cannot access 'price' before initialization let price = 50; They are registered at the start of the block, but cannot be accessed until the declaration line runs. The region between the start of the scope and the declaration is the Temporal Dead Zone (TDZ). The TDZ can be surprising: let x = 'outer'; function test() { console.log(x); // ReferenceError — the inner x is in its TDZ, shadowing the outer x let x = 'inner'; } Function expressions and arrow functions follow their variable's rules sayHi(); // TypeError: sayHi is not a function (it is undefined) var sayHi = function () { console.log('Hi'); }; sayBye(); // ReferenceError (TDZ) const sayBye = () => console.log('Bye'); Classes — hoisted with a TDZ const p = new Person(); // ReferenceError class Person {} Hoisting priority If a function declaration and a var share a name, the function declaration takes precedence during hoisting, until a later assignment overwrites the variable. Why it matters - Explains confusing bugs where variables are undefined instead of throwing errors. - Explains why functions can be called before they appear (useful for organising code with helper functions at the bottom). - Combined with var's function scope, it causes classic loop and closure problems. Best practices - Use const and let instead of var; the TDZ turns silent undefined bugs into clear errors. - Declare variables at the top of their scope or right before use for readability. - Do not rely on hoisting for variables; for functions, it is acceptable but keep code readable. - Use linters (no-use-before-define) to catch issues. Interview summary: "Hoisting means declarations are processed before code runs. Function declarations are fully available; var is hoisted and initialised to undefined; let, const and class are hoisted but stay in the temporal dead zone until their declaration executes, causing a ReferenceError if accessed early."
Ravindra Wadile · · 0 likes