0
0
Typescriptprogramming~20 mins

Optional parameters in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Optional Parameters in TypeScript Functions
📖 Scenario: You are building a simple greeting system for a website. Sometimes users provide their middle name, but sometimes they do not. You want to create a function that can greet users with or without their middle name.
🎯 Goal: Create a TypeScript function with an optional parameter to greet users by their full name or just first and last name.
📋 What You'll Learn
Create a function called greetUser with three parameters: firstName, lastName, and an optional middleName.
Set the middleName parameter as optional using TypeScript syntax.
Use the function to return a greeting string that includes the middle name if it is provided, or just first and last name if not.
Print the greeting for a user with a middle name and a user without a middle name.
💡 Why This Matters
🌍 Real World
Optional parameters are useful when you want to make your functions flexible. For example, greeting users with or without a middle name is common in real apps.
💼 Career
Understanding optional parameters is important for writing clean, reusable TypeScript code in many software development jobs.
Progress0 / 4 steps
1
Create the greetUser function with required parameters
Write a function called greetUser that takes two parameters: firstName and lastName, both of type string. The function should return a string greeting in the format: "Hello, firstName lastName!".
Typescript
Need a hint?

Use backticks ` to create a template string for the greeting.

2
Add an optional middleName parameter
Modify the greetUser function to add a third parameter called middleName of type string. Make this parameter optional using TypeScript syntax.
Typescript
Need a hint?

Add a question mark ? after middleName to make it optional.

3
Use the optional middleName in the greeting
Update the greetUser function to include the middleName in the greeting if it is provided. If middleName is not given, return the greeting with just firstName and lastName. Use an if statement to check if middleName exists.
Typescript
Need a hint?

Use an if statement to check if middleName is truthy before including it.

4
Print greetings with and without the optional parameter
Call the greetUser function twice: once with firstName = "John", middleName = "Paul", and lastName = "Smith"; and once with firstName = "Jane" and lastName = "Doe" only. Print both results using console.log.
Typescript
Need a hint?

Remember to call console.log for each greeting.