Optional parameters in Typescript - Time & Space Complexity
We want to see how adding optional parameters affects how long a function takes to run.
Does having optional inputs change the work the function does as input grows?
Analyze the time complexity of the following code snippet.
function greet(name: string, title?: string) {
if (title) {
return `Hello, ${title} ${name}!`;
}
return `Hello, ${name}!`;
}
const names = ["Alice", "Bob", "Charlie"];
for (const n of names) {
console.log(greet(n));
}
This code greets each name in a list, optionally adding a title if provided.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of names and calling the greet function once per name.
- How many times: Once for each name in the list (n times).
Each new name adds one more call to the greet function, which does a simple check and returns a string.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 greetings |
| 100 | About 100 greetings |
| 1000 | About 1000 greetings |
Pattern observation: The work grows directly with the number of names; doubling names doubles work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of names, regardless of optional parameters.
[X] Wrong: "Adding optional parameters makes the function slower for each call."
[OK] Correct: Optional parameters only add a simple check inside the function, which does not grow with input size, so they do not change the overall time growth.
Understanding how optional parameters affect time helps you explain function behavior clearly and shows you know how input size relates to work done.
"What if the greet function also loops through a list inside it? How would the time complexity change?"