Challenge - 5 Problems
Optional Parameters Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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'));
Attempts:
2 left
💡 Hint
Optional parameters can be omitted and are undefined if not passed.
✗ Incorrect
When
greet() is called without arguments, name is undefined, so the else branch runs returning 'Hello, stranger!'. When called with 'Anna', it returns 'Hello, Anna!'.❓ Predict Output
intermediate2: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));
Attempts:
2 left
💡 Hint
The
?? operator returns the right side if the left side is null or undefined.✗ Incorrect
If
b is not provided, it is undefined, so b ?? 2 evaluates to 2. So multiply(5) returns 5*2=10. multiply(5,3) returns 5*3=15.🔧 Debug
advanced2: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');
Attempts:
2 left
💡 Hint
Optional parameters can be undefined if not passed.
✗ Incorrect
Since
prefix is optional and not passed, it is undefined. Calling toUpperCase() on undefined causes a runtime TypeError.❓ Predict Output
advanced2: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.'));
Attempts:
2 left
💡 Hint
Default parameters are used if the argument is undefined.
✗ Incorrect
When lastName is omitted, the function returns title + firstName. The default title is 'Mr.'. When lastName is provided, it includes it. Passing undefined for lastName triggers default title usage.
❓ Predict Output
expert2: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));
Attempts:
2 left
💡 Hint
The
arguments object counts how many arguments were passed.✗ Incorrect
The
arguments.length property returns the number of arguments actually passed to the function, regardless of optional parameters.