Skip to content

Hoisting

Hoisting is JavaScript’s behavior of processing variable and function declarations before running any code, so they’re conceptually β€œmoved to the top” of their scope. How this plays out differs by declaration type: function declarations are hoisted fully (usable before their line); var declarations are hoisted but initialized to undefined; let/const are hoisted but stay in a β€œtemporal dead zone” β€” inaccessible until their declaration line runs.

console.log(greet()); // works! function declarations are fully hoisted
function greet() {
return "Hello!";
}
console.log(x); // undefined -- hoisted, but not yet assigned
var x = 5;
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 5;
// Function expressions are NOT hoisted the same way
console.log(sayHi()); // TypeError: sayHi is not a function
var sayHi = function () {
return "Hi!";
};

Relying on var hoisting and assuming a variable is β€œsafe” to use early just because it doesn’t throw β€” it silently returns undefined instead, which can mask bugs that let/const would catch immediately via a clear error.

function processUser() {
console.log(name); // undefined -- no error, but clearly wrong
var name = "Alice";
console.log(name); // "Alice"
}
// Using let surfaces the bug immediately and loudly
function processUser() {
console.log(name); // ReferenceError -- forces you to fix the ordering
let name = "Alice";
}
  1. Why can you call a function declaration before the line it’s defined on, but not a function stored in a const?

    AnswerFunction declarations are fully hoisted, including their body; const/let variables (even ones holding a function) are hoisted but remain inaccessible until their declaration line executes.
  2. What value does a var variable have if you read it before its declaration line?

    Answerundefined β€” the declaration is hoisted, but the assignment stays in place.
  3. What is the β€œtemporal dead zone”?

    AnswerThe period between entering a scope and reaching a let/const declaration, during which accessing that variable throws a ReferenceError instead of returning undefined.