Global execution context in Javascript - Time & Space 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.
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 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.
As the number of statements grows, the time to set up the global context grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 setup steps |
| 100 | About 100 setup steps |
| 1000 | About 1000 setup steps |
Pattern observation: Doubling the code lines roughly doubles the setup time.
Time Complexity: O(n)
This means the time to create the global execution context grows in direct proportion to the number of statements.
[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.
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.
"What if we added many function declarations inside the global context? How would the time complexity change?"