DEV Community

Arhan Khan
Arhan Khan

Posted on

Hoisting in JavaScript: Why Functions and Variables Behave Differently

Call a function before it is defined and it works. Use a variable before it is declared and you get an error — or worse, undefined. This strange behaviour has a name: hoisting. It is one of JavaScript's oldest quirks, and understanding it will save you from a whole class of confusing bugs.

During compilation, JavaScript moves declarations to the top of their scope before running any code. Function declarations are hoisted completely — the whole function is available before its line runs. That is why this works:

greet(); // "Hello!" — no error

function greet() {
  console.log("Hello!");
}
Enter fullscreen mode Exit fullscreen mode

Variables declared with var are also hoisted, but only the declaration — not the value. Until the assignment line runs, the variable exists but holds undefined. This is the source of many silent bugs: the code does not crash, it just reads the wrong value.

console.log(name); // undefined — not an error
var name = "Arhan";
console.log(name); // "Arhan"
Enter fullscreen mode Exit fullscreen mode

Variables declared with let and const behave differently. They are hoisted too, but they sit in a "temporal dead zone" — a period where the variable exists but cannot be used. Touching it before its declaration throws a ReferenceError, which is actually the helpful behaviour: it fails loudly instead of silently giving you undefined.

console.log(age); // ReferenceError: Cannot access 'age' before initialization
let age = 22;
Enter fullscreen mode Exit fullscreen mode

The practical rules are simple. Declare your variables at the top of their scope, before you use them. Prefer let and const over var — the dead zone turns a silent bug into an obvious error. And define your functions before calling them even when hoisting would let you get away with it, because code that reads top-to-bottom is code your future self can actually follow.

Top comments (0)