0
0
Javascriptprogramming~5 mins

What hoisting is in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: What hoisting is
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Since the function runs a fixed number of steps, the work does not grow with input size.

Input Size (n)Approx. Operations
102 console.log calls
1002 console.log calls
10002 console.log calls

Pattern observation: The number of operations stays the same no matter the input size.

Final Time Complexity

Time Complexity: O(1)

This means the code runs in constant time, doing the same amount of work regardless of input.

Common Mistake

[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.

Interview Connect

Understanding hoisting helps you explain how JavaScript runs code step-by-step, a key skill for clear coding and debugging.

Self-Check

"What if we replaced var with let in the example? How would the time complexity change?"