Block scope in Javascript - Time & Space Complexity
Let's explore how the time it takes to run code changes when we use block scope in JavaScript.
We want to see how the code's speed changes as the input size grows.
Analyze the time complexity of the following code snippet.
function printNumbers(n) {
for (let i = 0; i < n; i++) {
{
let temp = i * 2;
console.log(temp);
}
}
}
This code prints double the value of numbers from 0 up to n-1 using block scope inside the loop.
- Primary operation: The for-loop runs and prints a value each time.
- How many times: It runs exactly n times, once for each number from 0 to n-1.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times |
| 100 | 100 times |
| 1000 | 1000 times |
Pattern observation: The number of operations grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the input size.
[X] Wrong: "Using block scope inside the loop makes the code slower because it creates variables every time."
[OK] Correct: Creating variables inside a block is very fast and does not add extra loops or repeated heavy work. The main time is spent in the loop itself.
Understanding how loops and block scope affect time helps you explain code efficiency clearly and confidently.
"What if we added a nested loop inside the block scope? How would the time complexity change?"