Recall & Review
beginner
What is an optional parameter in TypeScript?
An optional parameter is a function parameter that may or may not be provided when the function is called. It is marked with a question mark (?) after the parameter name.
Click to reveal answer
beginner
How do you declare an optional parameter in a TypeScript function?
You add a question mark (?) after the parameter name in the function definition, like <code>function greet(name?: string)</code>.Click to reveal answer
beginner
What happens if you call a function without providing an optional parameter?
The optional parameter is undefined inside the function, so you can check if it was provided or not.
Click to reveal answer
intermediate
Can optional parameters be followed by required parameters in TypeScript?
No, optional parameters must come after all required parameters in the function signature.
Click to reveal answer
beginner
Example: What is the output of this code?<br><pre>function sayHi(name?: string) {<br> console.log(`Hi, ${name ?? 'friend'}!`);<br>}<br>sayHi();<br>sayHi('Anna');</pre>The output is:<br>
Hi, friend!<br>Hi, Anna!<br>Because when no name is given, it uses 'friend' as a default message.
Click to reveal answer
How do you mark a parameter as optional in TypeScript?
✗ Incorrect
Optional parameters are marked with a question mark (?) after the parameter name.
What is the type of an optional parameter if it is not provided when calling the function?
✗ Incorrect
If an optional parameter is not provided, its value is undefined inside the function.
Which of these function signatures is valid in TypeScript?
✗ Incorrect
Optional parameters must come after all required parameters.
What will this code print?<br>
function greet(name?: string) {<br> console.log(name || 'Guest');<br>}<br>greet();✗ Incorrect
Since name is undefined, the || operator returns 'Guest'.
Can you have multiple optional parameters in a TypeScript function?
✗ Incorrect
You can have multiple optional parameters, but they must come after all required parameters.
Explain how to use optional parameters in TypeScript functions and why they are useful.
Think about how to make some inputs to a function not mandatory.
You got /4 concepts.
Describe the rules about the order of optional and required parameters in TypeScript function definitions.
Consider what happens if you put an optional parameter before a required one.
You got /3 concepts.