Default parameters in TypeScript functions provide a way to initialize function parameters with default values if no value or undefined is passed during the function call. This feature enhances code readability and maintainability by reducing the need for additional checks or conditional statements to handle cases where parameters are not provided.
When defining a function, you can assign a default value to a parameter by using the assignment operator (=) followed by the desired value. If the caller does not provide a value for that parameter, the default value will be used instead. This is particularly useful in scenarios where certain parameters are optional, allowing developers to create more flexible and robust functions.
function functionName(param1: type = defaultValue, param2: type = defaultValue): returnType {
// function body
}
function greet(name: string = "Guest", age: number = 18): string {
return `Hello, ${name}. You are ${age} years old.`;
}
console.log(greet()); // Output: Hello, Guest. You are 18 years old.
console.log(greet("Alice")); // Output: Hello, Alice. You are 18 years old.
console.log(greet("Bob", 25)); // Output: Hello, Bob. You are 25 years old.
greet(undefined) will output "Hello, undefined. You are 18 years old."In conclusion, default parameters in TypeScript are a powerful feature that can simplify function definitions and enhance code clarity. By following best practices and avoiding common pitfalls, developers can create more efficient and user-friendly functions.