JavaScript · The language round
What is hoisting in JavaScript?
Short answer
Hoisting is the setup phase before code runs: var declarations become undefined, function declarations are fully initialised, and let/const are hoisted but stay in the temporal dead zone.
The engine does not physically move your code. Before executing a scope, it records the declarations it contains. What each declaration is initialised to depends on the kind of declaration.
console.log(hoistedVar); // undefined
var hoistedVar = 1;
sayHi(); // "hi"
function sayHi() {
console.log("hi");
}
console.log(notYet); // ReferenceError
let notYet = 2;What each declaration gets
var: hoisted and initialised toundefinedfunctiondeclaration: hoisted and fully callable before its lineletandconst: hoisted but uninitialised, so accessing them throws during the temporal dead zoneclass: behaves likelet; accessing it before the declaration throws
Function expressions follow the variable rules, not the function-declaration rules. A var holding a function expression is undefined until the assignment runs.
sayHi(); // TypeError: sayHi is not a function
var sayHi = function () {
console.log("hi");
};Common mistakes
- Saying everything is initialised to
undefined. Function declarations are not. - Saying
letandconstare not hoisted. They are hoisted but blocked by the temporal dead zone. - Relying on hoisting in production code. It makes control flow harder to read.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the temporal dead zone?
- 2Are function expressions hoisted?
- 3Are classes hoisted?
- 4How does hoisting interact with closures?
Say it in the interview
Before a scope runs, the engine records its declarations. var declarations are initialised to undefined, function declarations are fully created, and let and const are hoisted but uninitialised until their line executes. Accessing them before that throws because of the temporal dead zone. Function expressions and classes follow variable rules, not function-declaration rules.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.