Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.
✗ Incorrect
In TypeScript, optional parameters are declared by adding a question mark immediately after the parameter name, before the colon.
2fill in blank
mediumComplete 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'
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.
✗ Incorrect
Passing a string like 'Alice' uses the optional parameter. Passing undefined also works but here we want to show usage with a name.
3fill in blank
hardFix 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'
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.
✗ Incorrect
The correct syntax for optional parameters is to place a question mark immediately after the parameter name, before the colon.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using ?= which is not valid syntax.
Putting = before the type.
Omitting the question mark for optional parameters.
✗ Incorrect
Optional parameters use ?: and default values use = after the type.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using ?= which is invalid.
Forgetting the question mark for optional parameters.
Placing = before the type.
✗ Incorrect
Optional parameters use ?: and default values use = after the type. Both parameters are optional with defaults.