Bird
Raised Fist0
Typescriptprogramming~20 mins

Optional parameters in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Optional Parameters Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of function with optional parameter
What is the output of this TypeScript code when calling greet() and greet('Anna')?
Typescript
function greet(name?: string) {
  if (name) {
    return `Hello, ${name}!`;
  } else {
    return 'Hello, stranger!';
  }
}

console.log(greet());
console.log(greet('Anna'));
AHello, stranger!\nHello, Anna!
BHello, undefined!\nHello, Anna!
CHello, !\nHello, Anna!
DHello, stranger!\nHello, stranger!
Attempts:
2 left
💡 Hint
Optional parameters can be omitted and are undefined if not passed.
❓ Predict Output
intermediate
2:00remaining
Function call with missing optional parameter
What will be the output of this code snippet?
Typescript
function multiply(a: number, b?: number) {
  return a * (b ?? 2);
}

console.log(multiply(5));
console.log(multiply(5, 3));
A5\n15
B10\n6
CNaN\n15
D10\n15
Attempts:
2 left
💡 Hint
The ?? operator returns the right side if the left side is null or undefined.
🔧 Debug
advanced
2:00remaining
Identify the error with optional parameters
What error will this TypeScript code produce?
Typescript
function log(message: string, prefix?: string) {
  console.log(prefix.toUpperCase() + ': ' + message);
}

log('Hello');
ASyntaxError: Unexpected token
BTypeError: Cannot read property 'toUpperCase' of undefined
CNo error, outputs 'undefined: Hello'
DReferenceError: prefix is not defined
Attempts:
2 left
💡 Hint
Optional parameters can be undefined if not passed.
❓ Predict Output
advanced
2:00remaining
Output with default and optional parameters
What is the output of this code?
Typescript
function buildName(firstName: string, lastName?: string, title = 'Mr.') {
  if (lastName) {
    return `${title} ${firstName} ${lastName}`;
  } else {
    return `${title} ${firstName}`;
  }
}

console.log(buildName('John'));
console.log(buildName('John', 'Doe'));
console.log(buildName('John', undefined, 'Dr.'));
AMr. John\nMr. John Doe\nDr. John
BMr. John\nMr. John Doe\nMr. John
CJohn\nJohn Doe\nDr. John
DMr. John\nundefined\nDr. John
Attempts:
2 left
💡 Hint
Default parameters are used if the argument is undefined.
❓ Predict Output
expert
2:00remaining
Count of arguments with optional parameters
What will be the output of this code?
Typescript
function countArgs(a: number, b?: number, c?: number) {
  return arguments.length;
}

console.log(countArgs(1));
console.log(countArgs(1, 2));
console.log(countArgs(1, 2, 3));
A0\n1\n2
B3\n3\n3
C1\n2\n3
D1\n1\n1
Attempts:
2 left
💡 Hint
The arguments object counts how many arguments were passed.

Practice

(1/5)
1.

What does it mean when a function parameter in TypeScript is marked as optional with a ??

easy
A. The parameter is automatically set to zero.
B. You can call the function without providing that parameter.
C. The parameter is ignored inside the function.
D. The parameter must always be provided when calling the function.

Solution

  1. Step 1: Understand optional parameter meaning

    In TypeScript, a parameter marked with ? means it is optional and can be skipped when calling the function.
  2. Step 2: Compare with required parameters

    Required parameters must be given, but optional ones can be left out without error.
  3. Final Answer:

    You can call the function without providing that parameter. -> Option B
  4. Quick Check:

    Optional parameter means you can skip it [OK]
Hint: Optional parameters can be left out when calling functions [OK]
Common Mistakes:
  • Thinking optional means parameter is ignored
  • Assuming optional parameters must be last but not knowing why
  • Confusing optional with default parameters
2.

Which of the following is the correct way to declare a function with an optional parameter age of type number in TypeScript?

easy
A. function greet(name: string, age: number?) {}
B. function greet(name: string, ?age: number) {}
C. function greet(name: string, age?: number) {}
D. function greet(name: string, age: optional number) {}

Solution

  1. Step 1: Recall optional parameter syntax

    In TypeScript, optional parameters are declared by adding ? after the parameter name, before the colon and type.
  2. Step 2: Check each option

    function greet(name: string, age?: number) {} uses age?: number, which is correct. Options B, C, and D use invalid syntax.
  3. Final Answer:

    function greet(name: string, age?: number) {} -> Option C
  4. Quick Check:

    Optional parameter syntax = paramName?: type [OK]
Hint: Use ? right after parameter name for optional [OK]
Common Mistakes:
  • Placing ? after the type instead of the name
  • Using invalid keywords like 'optional'
  • Putting ? before parameter name
3.

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));
medium
A. 10 and 15
B. 5 and 15
C. 10 and 8
D. Error because b is optional

Solution

  1. Step 1: Analyze function behavior with optional parameter

    If b is provided, return a * b. Otherwise, return a * 2.
  2. Step 2: Evaluate calls

    First call: multiply(5) means b is undefined, so returns 5 * 2 = 10. Second call: multiply(5, 3) returns 5 * 3 = 15.
  3. Final Answer:

    10 and 15 -> Option A
  4. Quick Check:

    Optional param missing uses default logic [OK]
Hint: Optional param missing triggers alternate logic in function [OK]
Common Mistakes:
  • Assuming missing optional param causes error
  • Confusing default value with optional parameter
  • Misreading ternary condition
4.

Identify the error in this TypeScript function declaration:

function logMessage(message?: string, level: string) {
  console.log(`[${level}] ${message}`);
}
medium
A. Optional parameter must be last in the parameter list.
B. Optional parameters cannot be strings.
C. Function must return a value if it has optional parameters.
D. No error, this is valid syntax.

Solution

  1. Step 1: Recall rule about optional parameters order

    In TypeScript, optional parameters must come after all required parameters.
  2. Step 2: Check parameter order

    Here, message? is optional but placed before required level. This causes a syntax error.
  3. Final Answer:

    Optional parameter must be last in the parameter list. -> Option A
  4. Quick Check:

    Optional params must be last [OK]
Hint: Put all optional parameters after required ones [OK]
Common Mistakes:
  • Placing optional parameters before required ones
  • Thinking optional means default value
  • Ignoring TypeScript syntax rules
5.

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?

hard
A. function createUser(username: string, age?: number = 18) {}
B. function createUser(username: string, age?: number) { age = 18; }
C. function createUser(username: string, age?: number) { if (!age) age = 18; }
D. function createUser(username: string, age: number = 18) {}

Solution

  1. 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.
  2. Step 2: Check syntax and behavior

    function createUser(username: string, age: number = 18) {} correctly uses a default parameter age: number = 18, which means if age is 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.
  3. Final Answer:

    function createUser(username: string, age: number = 18) {} -> Option D
  4. Quick Check:

    Use default parameter for optional with default value [OK]
Hint: Use default parameter syntax for optional with default [OK]
Common Mistakes:
  • Using redundant ? with default parameter syntax
  • Setting default inside function body incorrectly
  • Confusing optional and default parameters
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard