0
0
Javascriptprogramming~5 mins

Common hoisting pitfalls in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Common hoisting pitfalls
O(n)
Understanding Time Complexity

When we write JavaScript, some things like variable and function declarations move to the top before code runs. This is called hoisting.

We want to see how this affects how long the code takes to run.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function example(arr) {
  console.log(x); // undefined due to hoisting
  var x = 10;
  for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
  }
}

example([1, 2, 3]);
    

This code shows variable hoisting and loops through an array to print values.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that goes through each item in the array.
  • How many times: It runs once for every element in the input array.
How Execution Grows With Input

As the array gets bigger, the loop runs more times, printing each item.

Input Size (n)Approx. Operations
10About 10 prints
100About 100 prints
1000About 1000 prints

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the input size.

Common Mistake

[X] Wrong: "Hoisting makes the code run faster because variables are moved up."

[OK] Correct: Hoisting only changes when declarations happen, not how many times code runs. The loop still runs once per item.

Interview Connect

Understanding hoisting helps you predict code behavior and spot bugs. Knowing how loops affect time helps you write efficient code.

Self-Check

"What if we replaced the for-loop with a nested loop over the same array? How would the time complexity change?"