Variable declaration using var in Javascript - Time & Space Complexity
Let's see how declaring variables with var affects the speed of a program.
We want to know how the time to run changes when we declare variables using var.
Analyze the time complexity of the following code snippet.
var a = 5;
var b = 10;
var c = a + b;
console.log(c);
This code declares three variables using var and prints their sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Variable declarations and simple arithmetic.
- How many times: Each line runs once, no loops or repeats.
Since there are no loops or repeated steps, the time to run grows linearly with the number of variables we declare.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: Time grows directly with the number of variable declarations.
Time Complexity: O(n)
This means the time grows in a straight line as you add more var declarations.
[X] Wrong: "Declaring variables with var takes constant time no matter how many variables."
[OK] Correct: Each variable declaration is a separate step, so more variables mean more steps and more time.
Understanding how simple statements like variable declarations affect time helps build a strong foundation for analyzing bigger code pieces.
"What if we replaced var with let or const? How would the time complexity change?"