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