Look at this code carefully. We call a function before it is written:
greet();
function greet() {
console.log("Hello!");
}Output:
Hello!It works! Now try the same idea with a variable:
console.log(city);
var city = "Pune";Output:
undefinedNo error, but also not "Pune". And if we use let instead of var, we get an error.
All three behaviours are explained by one concept: hoisting. It is one of the most common topics in JavaScript interviews, so let's understand it properly.
What is Hoisting?
Hoisting is JavaScript's behaviour of registering declarations (variables, functions and classes) at the start of their scope, before any code in that scope runs.
You'll often hear it described as "declarations are moved to the top". That is a helpful mental picture, but nothing actually moves. Your code stays exactly where you wrote it. What really happens is that the JavaScript engine reads the whole scope first and creates its variables and functions before running the code line by line.
How JavaScript Runs Your Code
When JavaScript enters a scope (the whole script, or a function when it is called), it works in two phases:
Phase 1: Creation (setup)
- Scan the scope for declarations
- function declarations → created with their full body
- var variables → created and set to undefined
- let / const / class → created but left UNINITIALIZED
Phase 2: Execution
- Run the code line by line
- Assignments (=) happen only now, when their line is reachedLet's apply this to our first two examples.
Creation phase:
greet → function greet() { console.log("Hello!"); }
city → undefined
Execution phase:
greet() → function already exists → prints "Hello!"
console.log(city) → city exists but is still undefined
city = "Pune" → only now does city get its valueEverything else in this chapter follows from these two phases.
Hoisting of Function Declarations
A function declaration is hoisted completely: its name and its body. That's why you can call it anywhere in its scope, even above the line where it's written.
console.log(add(2, 3));
console.log(square(4));
function add(a, b) {
return a + b;
}
function square(n) {
return n * n;
}Output:
5
16Some developers use this on purpose: they put the main logic at the top of a file and helper functions at the bottom.
Hoisting of var
A var declaration is hoisted, but only the declaration, not the assignment. During the creation phase, the variable is set to undefined.
console.log(score);
var score = 90;
console.log(score);Output:
undefined
90You can picture JavaScript treating the code like this:
var score; // declaration hoisted, value is undefined
console.log(score); // undefined
score = 90; // assignment stays in its original place
console.log(score); // 90This silent undefined is dangerous: the program doesn't crash, it just quietly uses the wrong value. That is a big reason modern JavaScript avoids var.
Hoisting of let and const
Here's a fact that surprises many people: let and const are hoisted too. The engine knows about them from the start of their block. But unlike var, they are not initialized. Touching them before their declaration line throws an error:
console.log(age);
let age = 25;Result:
ReferenceError: Cannot access 'age' before initializationThe same happens with const. (This is the exact message from Chrome and Node.js; other browsers word it slightly differently, but it is always a ReferenceError.)
The Temporal Dead Zone (TDZ)
The region from the start of the scope until the line where the variable is declared is called the Temporal Dead Zone.
The Temporal Dead Zone is the period during which a let, const or class binding exists but cannot be accessed, because it has not been initialized yet.
{
// ---- TDZ for message starts here ----
// console.log(message); → ReferenceError
// ---- TDZ ends on the next line ----
let message = "Hi";
console.log(message); // ✅ "Hi"
}The TDZ is a good thing. Instead of silently giving you undefined like var, JavaScript tells you immediately that you used a variable too early.
Proof That let Is Hoisted
If let were not hoisted at all, the code below would simply print the outer x. It doesn't:
let x = "outer";
{
console.log(x); // which x?
let x = "inner";
}Result:
ReferenceError: Cannot access 'x' before initializationWhen the block starts, the inner x is already registered for the whole block (it shadows the outer one, as we saw in the Scope chapter), but it is still in its TDZ. So console.log(x) refers to the inner x and fails.
"Not Defined" vs "Before Initialization"
These two errors look similar but mean different things:
Error message | Meaning |
|---|---|
| There is no variable named |
|
|
Even typeof, which is normally "safe", throws inside the TDZ:
console.log(typeof notDeclaredAnywhere); // safe for undeclared names
// try...catch catches the error so we can print it and keep going (covered in the Error Handling chapter)
try {
console.log(typeof total);
} catch (error) {
console.log(error.name + ": " + error.message);
}
let total = 100;Output:
undefined
ReferenceError: Cannot access 'total' before initializationFor a name that doesn't exist anywhere, typeof quietly returns "undefined". But for a let variable that exists and is still in its TDZ, even typeof throws. The rule is simple: never touch a let or const before its declaration line.
Function Expressions and Arrow Functions
Only function declarations are fully hoisted. A function expression or arrow function is just a value stored in a variable, so it follows the rules of that variable.
With var
try {
sayHi();
} catch (error) {
console.log(error.name + ": " + error.message);
}
var sayHi = function () {
console.log("Hi!");
};Output:
TypeError: sayHi is not a functionsayHi was hoisted as undefined, and calling undefined() is a TypeError.
With let or const
sayBye();
const sayBye = () => {
console.log("Bye!");
};Result:
ReferenceError: Cannot access 'sayBye' before initializationSo if you want to call a function before the line where it's written, it must be a function declaration.
Hoisting Happens in Every Scope
Hoisting isn't only about the top of the file. Every function call creates a new scope, and declarations are hoisted to the top of that scope.
var name = "Global";
function show() {
console.log(name);
var name = "Local";
console.log(name);
}
show();Output:
undefined
LocalMany people expect the first line to print "Global". But inside show(), the local var name is hoisted to the top of the function and starts as undefined. It shadows the global name for the entire function, even the lines above it.
var Ignores Blocks
Since var is function-scoped (see the Scope chapter), a var inside an if block is hoisted to the top of the whole function:
function checkDiscount(isMember) {
console.log(discount);
if (isMember) {
var discount = 10;
}
console.log(discount);
}
checkDiscount(false);Output:
undefined
undefinedEven though the if block never ran, discount exists in the whole function. With let, the first console.log would throw discount is not defined, which is much more honest.
When a Function and a var Share a Name
This one appears in interviews. What does this print?
console.log(typeof value);
var value = 10;
function value() {
return "I am a function";
}
console.log(typeof value);Output:
function
numberDuring the creation phase, the function declaration wins over the plain var declaration, so value starts as the function. Then, in the execution phase, the line value = 10 runs and replaces it with a number. (The function declaration line itself does nothing during execution, because it was already handled during setup.)
In real code, never reuse a name like this. With let or const, JavaScript wouldn't even allow it; you'd get a SyntaxError for declaring the same name twice.
What About Classes?
We'll learn classes later in this tutorial. For now, just remember that a class declaration behaves like let: it is hoisted, but it sits in the TDZ until its line runs. So you must define a class before you use it.
Hoisting at a Glance
Declaration | Hoisted? | Value before its line | Using it early gives |
|---|---|---|---|
| Yes (with body) | The full function | Works normally |
| Yes |
|
|
| Yes | Uninitialized (TDZ) |
|
| Yes | Uninitialized (TDZ) |
|
| Only |
|
|
| Only | Uninitialized (TDZ) |
|
Best Practices
Use
constby default andletwhen you need to reassign. Avoidvar; its hoisting toundefinedhides bugs.Declare variables at the top of their scope, or at least before you use them.
Don't rely on hoisting for variables. Relying on it for function declarations is fine and common.
Avoid declaring functions inside
ifblocks with thefunctionkeyword. Their hoisting rules inside blocks are complicated and differ between strict mode and older non-strict code. Useconst f = () => {}inside blocks instead.
Interview Questions
Try predicting the output before reading the answer.
Question 1
var a = 1;
function test() {
console.log(a);
var a = 2;
}
test();Output:
undefinedThe local var a is hoisted to the top of test() and shadows the global a.
Question 2
console.log(double(4));
console.log(triple);
function double(n) {
return n * 2;
}
var triple = function (n) {
return n * 3;
};Output:
8
undefineddouble is a function declaration (fully hoisted). triple is a var, so it is undefined until the assignment runs. We only log it here; calling triple(4) would throw a TypeError.
Question 3: "Are let and const hoisted?"
Answer: Yes. They are registered at the start of their block, but they are not initialized, so accessing them before the declaration throws a ReferenceError. That period is the Temporal Dead Zone.
Conclusion
Hoisting means JavaScript sets up all declarations in a scope before running the code in it.
Function declarations are hoisted with their body, so they can be called before they appear.
varis hoisted and initialized toundefined.let,constandclassare hoisted but stay in the Temporal Dead Zone until their line runs.Function expressions and arrow functions follow the rules of the variable that holds them.
Hoisting happens in every scope, not just at the top of the file.
With scope and hoisting understood, you're ready for one of JavaScript's most powerful features: closures.