Assignment operators in Javascript - Time & Space Complexity
Let's see how fast or slow assignment operators run in JavaScript.
We want to know how the time to do assignments changes when we have more data.
Analyze the time complexity of the following code snippet.
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
This code adds up all numbers in an array using the += assignment operator inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The assignment with addition (total += arr[i]) inside the loop.
- How many times: Once for each item in the array (arr.length times).
As the array gets bigger, the number of assignments grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments |
| 100 | 100 assignments |
| 1000 | 1000 assignments |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input size grows.
[X] Wrong: "Assignment operators take constant time no matter what, so loops don't affect time."
[OK] Correct: Each assignment inside a loop happens many times, so total time depends on how many times the loop runs.
Understanding how assignment inside loops affects time helps you explain code efficiency clearly and confidently.
"What if we replaced the for loop with a nested loop doing assignments inside? How would the time complexity change?"