Menu
Coddy logo textTech

Optional Parameters with '?'

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 25 of 73.

Sometimes you want to create functions where certain parameters are not always required. TypeScript provides the ? syntax to mark parameters as optional, meaning callers can choose whether or not to provide them when calling the function.

To make a parameter optional, you add a question mark after the parameter name but before the type annotation:

function greet(name: string, greeting?: string): string {
  if (greeting) {
    return greeting + ", " + name;
  }
  return "Hello, " + name;
}

In this example, name is required while greeting is optional. You can call this function with just the name (greet("Alice")) or with both parameters (greet("Alice", "Good morning")). Inside the function, optional parameters have the type string | undefined, so you should check if they exist before using them.

challenge icon

Challenge

Easy

Create a function named createUserProfile that takes two parameters: username of type string (required) and displayName of type string (optional). The function should return a string with an explicit return type annotation.

When both parameters are provided, the function should return: "Profile: [displayName] (@[username])"

When only the username is provided, the function should return: "Profile: @[username]"

Create another function named calculateDiscount that takes two parameters: price of type number (required) and membershipLevel of type string (optional). The function should return a number with an explicit return type annotation.

When both parameters are provided, the function should return the price reduced by 10% (multiply by 0.9).

When only the price is provided, the function should return the original price unchanged.

Test your functions by calling them with the following values and printing the results:

  • Call createUserProfile with "john_doe" and "John Doe"
  • Call createUserProfile with only "jane_smith"
  • Call calculateDiscount with 100 and "premium"
  • Call calculateDiscount with only 75

Print each result on a separate line in the order specified above.

Try it yourself

// TODO: Write your code here
// Create the createUserProfile function with proper type annotations
// Create the calculateDiscount function with proper type annotations

// Test the functions and print the results
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript