Function parameters in Javascript - Time & Space Complexity
We want to see how the time a function takes changes when we give it different inputs.
How does the number of parameters affect the work the function does?
Analyze the time complexity of the following code snippet.
function sum(a, b, c) {
return a + b + c;
}
const result = sum(1, 2, 3);
console.log(result);
This function adds three numbers given as parameters and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding three numbers once.
- How many times: Exactly one time per function call.
The function always adds three numbers, no matter what values are passed.
| Input Size (number of parameters) | Approx. Operations |
|---|---|
| 3 | 2 additions |
| 5 | Still 2 additions (function fixed) |
| 10 | Still 2 additions (function fixed) |
Pattern observation: The work does not grow with more parameters because the function only adds three fixed inputs.
Time Complexity: O(1)
This means the function takes the same amount of time no matter what numbers you give it.
[X] Wrong: "More parameters always mean more time needed."
[OK] Correct: If the function does a fixed amount of work, adding more parameters that are not processed in loops or repeated steps does not increase time.
Understanding how function parameters affect time helps you explain your code clearly and shows you know what really costs time in programs.
"What if the function added all numbers in an array parameter instead of just three fixed ones? How would the time complexity change?"