0
0
Typescriptprogramming~5 mins

Default parameters with types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Default parameters with types
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: The for-loop that runs to print the greeting.
  • How many times: It runs exactly times times, which depends on input.
How Execution Grows With 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
1010 prints
100100 prints
10001000 prints

Pattern observation: The number of operations grows in a straight line as times increases.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

Understanding how default parameters affect time helps you explain function behavior clearly and shows you can analyze code beyond just logic.

Self-Check

What if the function called another function inside the loop that also had a loop? How would the time complexity change?