What hoisting is in Javascript - Time & Space Complexity
We want to understand how hoisting affects the order and cost of running JavaScript code.
Specifically, how does hoisting change when and how many times parts of code run?
Analyze the time complexity of the following code snippet.
function example() {
console.log(a);
var a = 5;
console.log(a);
}
example();
This code shows variable usage before and after declaration to illustrate hoisting.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The function runs once, with two console.log calls.
- How many times: Each console.log runs once per function call.
Since the function runs a fixed number of steps, the work does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 console.log calls |
| 100 | 2 console.log calls |
| 1000 | 2 console.log calls |
Pattern observation: The number of operations stays the same no matter the input size.
Time Complexity: O(1)
This means the code runs in constant time, doing the same amount of work regardless of input.
[X] Wrong: "Hoisting makes the code run multiple times or loops behind the scenes."
[OK] Correct: Hoisting only moves declarations up before running code; it does not repeat or loop code.
Understanding hoisting helps you explain how JavaScript runs code step-by-step, a key skill for clear coding and debugging.
"What if we replaced var with let in the example? How would the time complexity change?"