JavaScriptMedium
What is hoisting in JavaScript?
Hoisting is the effect of JavaScript creating every declaration in a scope before running that scope's code, so names exist from the top of the scope even though the code that sets them comes later.
Nothing is physically moved. When the engine enters a scope it first does a setup pass and registers all declarations. What differs is how each kind is initialised:
- Function declarations are fully initialised with their body. You can call them before the line where they appear.
varis initialised toundefined. Reading it early givesundefined, not an error.let,constandclassare registered but left uninitialised. Touching them before the declaration line throws aReferenceError. This window is the temporal dead zone (TDZ).- Function expressions and arrow functions follow the rules of the variable that holds them, so
var fn = () => {}isundefinedearly andconst fn = ...is in the TDZ.
Why it matters
- Calling a function declaration before it is defined is legitimate and common (e.g. helper functions at the bottom of a file).
- Relying on
varbeingundefinedearly hides bugs. The TDZ exists to turn those silent bugs into loud errors.
Interview tip
Say "declarations are processed before execution" rather than "moved to the top", and explain the TDZ for let/const.
Code example
js
1console.log(sayHi()); // "hi" - function declarations are fully hoisted2function sayHi() {3 return "hi";4}56console.log(count); // undefined - var is hoisted and set to undefined7var count = 5;89try {10 console.log(total); // ReferenceError: in the temporal dead zone11} catch (e) {12 console.log(e.name); // ReferenceError13}14let total = 10;1516try {17 greet(); // TypeError: greet is not a function (it's undefined right now)18} catch (e) {19 console.log(e.name); // TypeError20}21var greet = function () {22 return "hello";23};24console.log(greet()); // "hello"
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.