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