0
0
Typescriptprogramming~20 mins

Default parameters with types in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Default 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 default typed parameters
What is the output of this TypeScript function when called as greet()?
Typescript
function greet(name: string = "Guest", age: number = 30): string {
  return `Hello, ${name}! You are ${age} years old.`;
}

console.log(greet());
ATypeError: greet is not a function
B"Hello, undefined! You are undefined years old."
C"Hello, ! You are 0 years old."
D"Hello, Guest! You are 30 years old."
Attempts:
2 left
💡 Hint
Check the default values assigned to the parameters in the function signature.
Predict Output
intermediate
2:00remaining
Effect of overriding default parameters
What will be the output when calling calculateArea(5) with this function?
Typescript
function calculateArea(width: number, height: number = width): number {
  return width * height;
}

console.log(calculateArea(5));
A25
BNaN
C5
DTypeError: height is undefined
Attempts:
2 left
💡 Hint
Look at how the default value for height depends on width.
🔧 Debug
advanced
2:00remaining
Identify the error with default parameter types
What error does this TypeScript code produce?
Typescript
function multiply(a: number = 2, b: number): number {
  return a * b;
}

console.log(multiply(undefined, 3));
AError: A required parameter cannot follow an optional parameter
BTypeError: b is undefined
CNaN
D6
Attempts:
2 left
💡 Hint
Check the order of parameters with and without default values.
Predict Output
advanced
2:00remaining
Output with complex default parameter expressions
What is the output of this code?
Typescript
function buildName(firstName: string, lastName: string = firstName.toUpperCase()): string {
  return `${firstName} ${lastName}`;
}

console.log(buildName("john"));
A"john john"
B"john JOHN"
C"undefined undefined"
DTypeError: Cannot read property 'toUpperCase' of undefined
Attempts:
2 left
💡 Hint
The default value for lastName uses firstName's value.
🧠 Conceptual
expert
2:00remaining
Understanding default parameter evaluation timing
Consider this TypeScript code. What will be the output when foo() is called?
Typescript
let x = 10;
function foo(a: number = x) {
  console.log(a);
}

x = 20;
foo();
AReferenceError: x is not defined
Bundefined
C20
D10
Attempts:
2 left
💡 Hint
Default parameters are evaluated at call time, not at function definition time.