0
0
Typescriptprogramming~5 mins

Optional parameters in Typescript - Time & Space Complexity

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

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

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
10About 10 greetings
100About 100 greetings
1000About 1000 greetings

Pattern observation: The work grows directly with the number of names; doubling names doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of names, regardless of optional parameters.

Common Mistake

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

Interview Connect

Understanding how optional parameters affect time helps you explain function behavior clearly and shows you know how input size relates to work done.

Self-Check

"What if the greet function also loops through a list inside it? How would the time complexity change?"