0
0
Javascriptprogramming~5 mins

Assignment operators in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Assignment operators
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

As the array gets bigger, the number of assignments grows in the same way.

Input Size (n)Approx. Operations
1010 assignments
100100 assignments
10001000 assignments

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input size grows.

Common Mistake

[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.

Interview Connect

Understanding how assignment inside loops affects time helps you explain code efficiency clearly and confidently.

Self-Check

"What if we replaced the for loop with a nested loop doing assignments inside? How would the time complexity change?"