Back to Course

Learn TypeScript

0% Complete
0/0 Steps
Lesson 14 of 25
In Progress

Optional and Default Parameters in Typescript Functions

In TypeScript, optional and default parameters allow you to specify parameters in a function declaration that are not required to be passed when the function is called. This can be useful when you want to provide default values for parameters or allow the caller to omit certain parameters.

Optional Parameters:

To declare an optional parameter in a function, you can use the “?” symbol after the parameter name. For example:

function greet(name?: string): string {
  return `Hello, ${name || 'there'}!`;
}

console.log(greet()); // Outputs: "Hello, there!"
console.log(greet('John')); // Outputs: "Hello, John!"

In this example, the “name” parameter is declared as an optional parameter using the “?” symbol. The function body uses the “||” operator to provide a default value of “there” if the “name” parameter is not provided.

You can also specify multiple optional parameters in a function declaration by using the “?” symbol after each parameter name. For example:

function greet(firstName?: string, lastName?: string): string {
  return `Hello, ${firstName || 'there'} ${lastName || ''}!`;
}

console.log(greet()); // Outputs: "Hello, there!"
console.log(greet('John')); // Outputs: "Hello, John!"
console.log(greet('John', 'Doe')); // Outputs: "Hello, John Doe!"

In this example, the “firstName” and “lastName” parameters are both declared as optional parameters using the “?” symbol. The function body uses the “||” operator to provide default values for each parameter if they are not provided.

Default Parameters:

In addition to optional parameters, TypeScript also supports default parameters. Default parameters allow you to specify a default value for a parameter in the function declaration that will be used if the parameter is not provided when the function is called.

To declare a default parameter, you can use the “=” symbol followed by the default value after the parameter name. For example:

function greet(name: string = 'there'): string {
  return `Hello, ${name}!`;
}

console.log(greet()); // Outputs: "Hello, there!"
console.log(greet('John')); // Outputs: "Hello, John!"

In this example, the “name” parameter is declared with a default value of “there” using the “=” symbol. If the “name” parameter is not provided when the function is called, the default value will be used. If the “name” parameter is provided, the default value will be overridden.

You can also specify multiple default parameters in a function declaration by using the “=” symbol followed by the default value after each parameter name. For example:

function greet(firstName: string = 'there', lastName: string = ''): string {
  return `Hello, ${firstName} ${lastName}!`;
}

console.log(greet()); // Outputs: "Hello, there!"
console.log(greet('John')); // Outputs: "Hello, John!"
console.log(greet('John', 'Doe')); // Outputs: "Hello, John Doe!"

In this example, the “firstName” and “lastName” parameters are both declared with default values using the “=” symbol. If either parameter is not provided when the function is called, the default value will be used. If either parameter is provided, the default value will be overridden.

Why Should You Use Optional and Default Parameters?

Optional and default parameters can be useful in a number of situations. For example:

  • Providing default values for parameters can make it easier for the caller to use the function, as they don’t have to provide every parameter every time.
  • Using optional parameters can make it easier to add new functionality to a function without breaking existing code that calls the function.
  • Optional and default parameters can help reduce the number of overloads required for a function, as you can use optional and default parameters to handle a range of possible parameter combinations.

Conclusion

In this article, we learned about optional and default parameters in TypeScript. We saw how to use the “?” symbol to declare optional parameters and the “=” symbol to declare default parameters. We also looked at some of the benefits of using optional and default parameters in your code. Understanding how to use optional and default parameters can help you write more flexible and reusable code in your TypeScript projects.

Exercises

To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.

Write a function named “greet” that takes an optional parameter “name” and returns a greeting based on the value of “name”. Use an optional parameter and a default value to specify the parameter.

function greet(name: string = 'there'): string {
  return `Hello, ${name}!`;
}

console.log(greet()); // Outputs: "Hello, there!"
console.log(greet('John')); // Outputs: "Hello, John!"

Write a function named “addNumbers” that takes two optional parameters “x” and “y” and returns the sum of the two numbers. Use optional parameters and default values to specify the parameters.

function addNumbers(x: number = 0, y: number = 0): number {
  return x + y;
}

console.log(addNumbers()); // Outputs: 0
console.log(addNumbers(1)); // Outputs: 1
console.log(addNumbers(1, 2)); // Outputs: 3

Write a class named “Person” that has three private properties: “name”, “age”, and “phoneNumber”. Add getters and setters for each property and use default values to specify the default values for the “age” and “phoneNumber” properties.

class Person {
  private _name: string;
  private _age: number = 0;
  private _phoneNumber: string = '';

  get name(): string {
    return this._name;
  }

  set name(value: string) {
    this._name = value;
  }

  get age(): number {
    return this._age;
  }

  set age(value: number) {
    this._age = value;
  }

  get phoneNumber(): string {
    return this._phoneNumber;
  }

  set phoneNumber(value: string) {
    this._phoneNumber = value;
  }
}

class Person {
  // your code here
}

const person = new Person();
person.name = 'John';
console.log(person.name); // Outputs: "John"
console.log(person.age); // Outputs: 0
console.log(person.phoneNumber); // Outputs: ""

Write a function named “formatPhoneNumber” that takes a string parameter “phoneNumber” and returns the phone number in a standardized format. Use a default value to specify the default value for the “phoneNumber” parameter.

function formatPhoneNumber(phoneNumber: string = '123-456-7890'): string {
  const formattedPhoneNumber = phoneNumber.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
  return formattedPhoneNumber;
}

console.log(formatPhoneNumber()); // Outputs: "123-456-7890"
console.log(formatPhoneNumber('1234567890')); // Outputs: "123-456-7890"

Write a function named “calculateTotal” that takes two optional parameters “price” and “quantity” and returns the total cost of the purchase. Use optional parameters and default values to specify the parameters.

function calculateTotal(price: number = 0, quantity: number = 1): number {
  return price * quantity;
}

console.log(calculateTotal()); // Outputs: 0
console.log(calculateTotal(10)); // Outputs: 10
console.log(calculateTotal(10, 2)); // Outputs: 20