Fundamentalsbeginner

Hoisting Explained

Why function and variable declarations appear to be 'moved' to the top of their scope before code runs.

Hoisting is one of the most commonly misunderstood JavaScript behaviors, and it is a near-guaranteed interview question because it explains a lot of seemingly weird code. The core idea is that the JavaScript engine processes declarations in a scope during a compile-like phase before executing any code line by line, which is why you can call a function before its definition appears in the source.

It's like a conference program printed in advance: every speaker's name is listed at the top (hoisted), but if you show up to a talk before the actual speaker arrives, the room is empty (temporal dead zone) rather than having no name on the schedule at all.

Key Concepts

1
Function declarations are hoisted completely — both the name and the function body are available from the top of the enclosing scope, which is why sayHi() works even if the call is written before the function sayHi() {} block. Variable declarations behave differently depending on the keyword: var is hoisted and initialized to undefined, so reading it early gives undefined rather than an error. let and const are hoisted but not initialized, leaving them in the temporal dead zone, so reading them before their declaration line throws a ReferenceError.
sayHi()function sayHi() {}varundefinedlet
2
Function expressions and arrow functions assigned to variables follow the variable's hoisting rules, not the function's. So const greet = () => {} cannot be called before that line runs, because greet is just a const binding that happens to hold a function value, and it is subject to the temporal dead zone like any other const.
const greet = () => {}greetconst
3
Understanding hoisting matters less for writing clever hoisted code and more for avoiding bugs: relying on hoisting makes code harder to read, and modern style guides recommend declaring variables and functions before use regardless of what hoisting technically allows.