Unary operators in Javascript - Time & Space Complexity
Unary operators perform simple actions on a single value. We want to see how their use affects the time it takes for code to run.
How does the number of unary operations grow as input size changes?
Analyze the time complexity of the following code snippet.
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
numbers[i] = -numbers[i];
}
This code uses a unary minus operator to change each number to its negative inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Applying the unary minus operator to each element.
- How many times: Once for each element in the array.
Each element gets processed once, so the work grows directly with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 unary operations |
| 100 | 100 unary operations |
| 1000 | 1000 unary operations |
Pattern observation: Doubling the input doubles the number of unary operations.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items.
[X] Wrong: "Unary operators run instantly and don't add to time complexity."
[OK] Correct: Even simple operations take time, and when repeated many times, they add up proportionally to input size.
Understanding how simple operations inside loops affect performance helps you explain code efficiency clearly and confidently.
"What if we replaced the unary minus with a function call inside the loop? How would the time complexity change?"