0
0
Typescriptprogramming~5 mins

Declaring global variables in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Declaring global variables
O(n)
Understanding Time Complexity

When we declare global variables, we want to know how it affects the program's speed as it runs.

We ask: Does adding global variables make the program slower as it grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


let count = 0;

function increment() {
  count += 1;
}

increment();
increment();

This code declares a global variable count and a function that increases it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Simple variable assignment and addition.
  • How many times: Each call to increment() runs once, no loops or recursion.
How Execution Grows With Input

Execution time stays about the same no matter how many global variables are declared.

Input Size (number of global variables)Approx. Operations
1010 simple assignments
100100 simple assignments
10001000 simple assignments

Pattern observation: Adding more global variables increases operations linearly, but each operation is very simple and does not repeat inside loops.

Final Time Complexity

Time Complexity: O(n)

This means declaring or using global variables takes time proportional to the number of variables accessed or modified.

Common Mistake

[X] Wrong: "Declaring many global variables makes the program slower because it has to manage all of them every time."

[OK] Correct: Each global variable is stored once and accessed directly; no repeated work happens just because they exist.

Interview Connect

Understanding that global variables themselves do not add time cost helps you focus on what really affects performance, like loops or heavy calculations.

Self-Check

"What if we added a loop that updates a global variable many times? How would the time complexity change?"