Default parameters with types in Typescript - Time & Space Complexity
We want to see how the time it takes to run a function changes when it uses default parameters with types.
Specifically, does adding default values affect how long the function takes as input grows?
Analyze the time complexity of the following code snippet.
function greet(name: string = "Guest", times: number = 1): void {
for (let i = 0; i < times; i++) {
console.log(`Hello, ${name}!`);
}
}
// Calling greet("Alice", 3) prints "Hello, Alice!" 3 times
This function prints a greeting message multiple times, using default values if no arguments are given.
- Primary operation: The for-loop that runs to print the greeting.
- How many times: It runs exactly
timestimes, which depends on input.
Each time we increase the times parameter, the loop runs more times, so the work grows directly with times.
| Input Size (times) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The number of operations grows in a straight line as times increases.
Time Complexity: O(n)
This means the time to run the function grows directly in proportion to the number of times it prints the message.
[X] Wrong: "Default parameters make the function slower or faster depending on their types."
[OK] Correct: Default parameters only set values if none are given; they do not add loops or extra work, so they don't affect how the time grows with input size.
Understanding how default parameters affect time helps you explain function behavior clearly and shows you can analyze code beyond just logic.
What if the function called another function inside the loop that also had a loop? How would the time complexity change?