0
0
Javascriptprogramming~5 mins

Block scope in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Block scope
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

As n grows, the number of times the loop runs grows the same way.

Input Size (n)Approx. Operations
1010 times
100100 times
10001000 times

Pattern observation: The number of operations grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

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

Interview Connect

Understanding how loops and block scope affect time helps you explain code efficiency clearly and confidently.

Self-Check

"What if we added a nested loop inside the block scope? How would the time complexity change?"