0
0
Javascriptprogramming~5 mins

Variable hoisting behavior in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Variable hoisting behavior
O(n)
Understanding Time Complexity

Let's explore how variable hoisting affects the speed of running JavaScript code.

We want to see how the number of steps changes when variables are hoisted.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function example(arr) {
  for (let i = 0; i < arr.length; i++) {
    var temp = arr[i] * 2;
    console.log(temp);
  }
}
    

This code loops through an array, doubles each item, and prints it. The variable temp is declared inside the loop using var.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop runs through each item in the array.
  • How many times: It runs once for every element in the array, so as many times as the array length.
How Execution Grows With Input

As the array gets bigger, the loop runs more times, doing the same steps each time.

Input Size (n)Approx. Operations
10About 10 times the steps inside the loop
100About 100 times the steps inside the loop
1000About 1000 times the steps inside the loop

Pattern observation: The work grows directly with the size of the input array.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the code grows in a straight line as the input gets bigger.

Common Mistake

[X] Wrong: "Declaring var inside the loop means it runs multiple times and slows down the code a lot."

[OK] Correct: In JavaScript, var declarations are hoisted to the top of the function, so the variable is created once, not repeatedly, which means it does not add extra time per loop.

Interview Connect

Understanding how variable hoisting works helps you explain why some code runs faster or slower, showing you know how JavaScript handles variables behind the scenes.

Self-Check

"What if we changed var to let inside the loop? How would the time complexity change?"