0
0
Javascriptprogramming~5 mins

Global execution context in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Global execution context
O(n)
Understanding Time Complexity

When JavaScript runs code, it creates a global execution context first. This context sets up the environment for the whole program.

We want to know how the time to create this global context changes as the code size grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const a = 10;
const b = 20;
function sum(x, y) {
  return x + y;
}
const result = sum(a, b);
console.log(result);
    

This code declares variables and a function, then calls the function and logs the result.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: There are no loops or repeated operations here.
  • How many times: Each statement runs once during the global execution context creation.
How Execution Grows With Input

As the number of statements grows, the time to set up the global context grows linearly.

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

Pattern observation: Doubling the code lines roughly doubles the setup time.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the global execution context grows in direct proportion to the number of statements.

Common Mistake

[X] Wrong: "The global execution context runs instantly no matter how big the code is."

[OK] Correct: Even though it feels fast, the engine must process each line once, so more code means more setup time.

Interview Connect

Understanding how the global execution context scales helps you explain how JavaScript prepares your code before running it. This skill shows you grasp the basics of how programs start.

Self-Check

"What if we added many function declarations inside the global context? How would the time complexity change?"