Variable hoisting behavior in Javascript - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop 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.
As the array gets bigger, the loop runs more times, doing the same steps each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times the steps inside the loop |
| 100 | About 100 times the steps inside the loop |
| 1000 | About 1000 times the steps inside the loop |
Pattern observation: The work grows directly with the size of the input array.
Time Complexity: O(n)
This means the time to run the code grows in a straight line as the input gets bigger.
[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.
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.
"What if we changed var to let inside the loop? How would the time complexity change?"