Hoisting
Sometimes JavaScript behaves in a way that feels unexpected. Code seems to work even when things are written out of order.
This behavior is called hoisting. Understanding hoisting helps you avoid confusion and bugs.
What Is Hoisting?
Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before the code is executed.
Only declarations are hoisted, not actual values.
Hoisting with var
Variables declared with var are hoisted
and initialized with undefined.
console.log(score);
var score = 10;
Even though score is declared later,
JavaScript knows about it during execution.
Hoisting with let and const
Variables declared with let and const
are also hoisted, but they are not initialized.
Accessing them before declaration causes an error.
console.log(total);
let total = 50;
This behavior is related to something called the Temporal Dead Zone, which you will explore more deeply later.
Hoisting with Functions
Function declarations are fully hoisted. This means they can be called before they are defined.
greet();
function greet() {
console.log("Hello from Dataplexa");
}
This works because the entire function definition is hoisted.
Function Expressions Are Different
Function expressions behave like variables. They are not hoisted in the same way.
sayHello();
const sayHello = function () {
console.log("Hi");
};
This will result in an error because the function is not available before initialization.
Real-World Analogy
Think of hoisting like planning a meeting:
- The meeting is scheduled (declaration)
- The agenda is prepared later (value)
JavaScript knows what exists before it knows the details.
Common Beginner Mistakes
- Using variables before declaring them
- Relying on
varhoisting - Calling function expressions too early
Clear code order avoids hoisting-related confusion.
Thumb Rules
- Always declare variables at the top of their scope
- Prefer
letandconst - Avoid relying on hoisting behavior
- Write code in the order it should run
More on Hoisting Later
This lesson introduced hoisting at a beginner-friendly level.
More detailed execution behavior is covered later.
- Execution order and scope chains are explained in Lesson 43 (Execution Context)
- Advanced function behavior is discussed in Lesson 34 (Modules)
What Comes Next?
Now that you understand how JavaScript processes declarations, the next step is learning how to store and manage collections of data.
In the next lesson, we will learn about arrays.