Why variables are needed in Javascript - Performance Analysis
We want to see how using variables affects the steps a program takes.
How does the program's work change when it stores and reuses values?
Analyze the time complexity of the following code snippet.
let a = 5;
let b = 10;
let sum = a + b;
console.log(sum);
This code stores numbers in variables, adds them, and prints the result.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Simple addition and variable assignment.
- How many times: Each operation happens once, no loops or repeats.
Since there are no loops or repeated steps, the work stays the same no matter the input.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 4 |
| 100 | 4 |
| 1000 | 4 |
Pattern observation: The number of steps does not grow with input size.
Time Complexity: O(1)
This means the program takes the same amount of time no matter how big the input is.
[X] Wrong: "Using variables makes the program slower because it adds extra steps."
[OK] Correct: Variables just store values and do not add repeated work, so they don't slow down the program as input grows.
Understanding how variables affect program steps helps you explain your code clearly and shows you know how programs work efficiently.
"What if we replaced variables with repeated calculations? How would the time complexity change?"