0
0
Typescriptprogramming~10 mins

Optional parameters in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare an optional parameter in the function.

Typescript
function greet(name[1] string) {
  console.log(`Hello, ${name}!`);
}
Drag options to blanks, or click blank then click option'
A? :
B:?
C?:
D?:=
Attempts:
3 left
💡 Hint
Common Mistakes
Putting the question mark after the colon.
Using spaces between the question mark and colon.
Using an equal sign with the question mark.
2fill in blank
medium

Complete the function call to use the optional parameter correctly.

Typescript
function greet(name?: string) {
  if (name) {
    console.log(`Hello, ${name}!`);
  } else {
    console.log('Hello!');
  }
}

greet([1]);
Drag options to blanks, or click blank then click option'
A'Alice'
Bundefined
Cnull
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Passing null which is not the same as undefined in TypeScript optional parameters.
Passing 0 which is a number, not a string.
Passing undefined when the goal is to provide a name.
3fill in blank
hard

Fix the error in the function declaration to make the second parameter optional.

Typescript
function multiply(a: number, b[1] number): number {
  return a * b;
}
Drag options to blanks, or click blank then click option'
A?:
B?:=
C:?
D? :
Attempts:
3 left
💡 Hint
Common Mistakes
Putting the question mark after the colon.
Using spaces between the question mark and colon.
Using an equal sign with the question mark.
4fill in blank
hard

Fill both blanks to create a function with an optional parameter and a default value.

Typescript
function greet(name[1] string[2] = 'Guest') {
  console.log(`Hello, ${name}!`);
}
Drag options to blanks, or click blank then click option'
A?:
B=
C ?=
D:
Attempts:
3 left
💡 Hint
Common Mistakes
Using ?= which is not valid syntax.
Putting = before the type.
Omitting the question mark for optional parameters.
5fill in blank
hard

Fill all three blanks to create a function with two optional parameters and default values.

Typescript
function createUser(name[1] string[2] = 'Anonymous', age[3] number[4] = 18) {
  console.log(`Name: ${name}, Age: ${age}`);
}
Drag options to blanks, or click blank then click option'
A?:
B=
C ?=
D:
Attempts:
3 left
💡 Hint
Common Mistakes
Using ?= which is invalid.
Forgetting the question mark for optional parameters.
Placing = before the type.