0
0
Typescriptprogramming~20 mins

Optional parameters in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 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.