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?"
Practice
What does it mean when a function parameter in TypeScript is marked as optional with a ??
Solution
Step 1: Understand optional parameter meaning
In TypeScript, a parameter marked with?means it is optional and can be skipped when calling the function.Step 2: Compare with required parameters
Required parameters must be given, but optional ones can be left out without error.Final Answer:
You can call the function without providing that parameter. -> Option BQuick Check:
Optional parameter means you can skip it [OK]
- Thinking optional means parameter is ignored
- Assuming optional parameters must be last but not knowing why
- Confusing optional with default parameters
Which of the following is the correct way to declare a function with an optional parameter age of type number in TypeScript?
Solution
Step 1: Recall optional parameter syntax
In TypeScript, optional parameters are declared by adding?after the parameter name, before the colon and type.Step 2: Check each option
function greet(name: string, age?: number) {} usesage?: number, which is correct. Options B, C, and D use invalid syntax.Final Answer:
function greet(name: string, age?: number) {} -> Option CQuick Check:
Optional parameter syntax =paramName?: type[OK]
? right after parameter name for optional [OK]- Placing
?after the type instead of the name - Using invalid keywords like 'optional'
- Putting
?before parameter name
What will be the output of this TypeScript code?
function multiply(a: number, b?: number) {
return b ? a * b : a * 2;
}
console.log(multiply(5));
console.log(multiply(5, 3));Solution
Step 1: Analyze function behavior with optional parameter
Ifbis provided, returna * b. Otherwise, returna * 2.Step 2: Evaluate calls
First call:multiply(5)meansbis undefined, so returns5 * 2 = 10. Second call:multiply(5, 3)returns5 * 3 = 15.Final Answer:
10 and 15 -> Option AQuick Check:
Optional param missing uses default logic [OK]
- Assuming missing optional param causes error
- Confusing default value with optional parameter
- Misreading ternary condition
Identify the error in this TypeScript function declaration:
function logMessage(message?: string, level: string) {
console.log(`[${level}] ${message}`);
}Solution
Step 1: Recall rule about optional parameters order
In TypeScript, optional parameters must come after all required parameters.Step 2: Check parameter order
Here,message?is optional but placed before requiredlevel. This causes a syntax error.Final Answer:
Optional parameter must be last in the parameter list. -> Option AQuick Check:
Optional params must be last [OK]
- Placing optional parameters before required ones
- Thinking optional means default value
- Ignoring TypeScript syntax rules
You want to write a function createUser that takes a required username and an optional age. If age is not provided, it should default to 18. Which of these is the best way to declare the function?
Solution
Step 1: Understand difference between optional and default parameters
Optional parameters can be omitted but have no default value unless assigned. Default parameters have a default value and are optional by nature.Step 2: Check syntax and behavior
function createUser(username: string, age: number = 18) {} correctly uses a default parameterage: number = 18, which means ifageis omitted, it defaults to 18. function createUser(username: string, age?: number = 18) {} (age?: number = 18) is valid syntax but the?is redundant since default parameters are already optional. Options B and D do not set default properly and may cause issues.Final Answer:
function createUser(username: string, age: number = 18) {} -> Option DQuick Check:
Use default parameter for optional with default value [OK]
- Using redundant
?with default parameter syntax - Setting default inside function body incorrectly
- Confusing optional and default parameters
Ready to prove it?
Pass the test and this pattern moves unknown
