Optional and Default Parameters in TypeScript
Learn how to make function parameters optional and how to assign default values to parameters in TypeScript.
What Will We Learn?
Sometimes, a function needs to accept different numbers of arguments. TypeScript supports optional parameters and default parameters to handle these situations.
- Understand optional function parameters.
- Use the question mark symbol with optional parameters.
- Assign default values to parameters.
- Understand the difference between optional and default parameters.
- Use these parameters in practical examples.
Optional and Default Parameters Workflow
Follow these steps to understand how TypeScript handles optional and default parameters.
Step 1
Define ParametersDeclare required, optional, or default parameters.
Step 2
Call FunctionPass the arguments you need.
Step 3
Resolve ValuesUse supplied values or default values.
Step 4
Execute FunctionProcess the available parameter values.
1. Optional Parameters in TypeScript
An optional parameter allows a function to be called
without providing a value for that parameter.
Use the question mark symbol ? after
the parameter name.
Syntax
function functionName(
requiredParameter: string,
optionalParameter?: string
): void {
// Function statements
}
Example
function greetStudent(name: string, course?: string): void {
console.log("Student:", name);
console.log("Course:", course);
}
greetStudent("Rahul");
greetStudent("Priya", "TypeScript");
Expected Output
Student: Rahul
Course: undefined
Student: Priya
Course: TypeScript
Explanation
-
nameis a required parameter. -
course?is an optional parameter. -
The first function call does not supply a course,
so its value is
undefined. - The second call supplies a course name.
2. Checking Optional Parameters
An optional parameter may be undefined when the caller does not provide an argument. We can check its value before using it.
Example
function displayCourse(
studentName: string,
course?: string
): void {
console.log("Student:", studentName);
if (course !== undefined) {
console.log("Course:", course);
} else {
console.log("Course: Not selected");
}
}
displayCourse("Amit");
displayCourse("Priya", "Java Full Stack");
Expected Output
Student: Amit
Course: Not selected
Student: Priya
Course: Java Full Stack
Explanation
The function checks whether course is
undefined. If a course is supplied, it displays
the course name; otherwise, it displays a message
indicating that no course has been selected.
3. Default Parameters in TypeScript
A default parameter has a predefined value.
When the caller omits the corresponding argument
or passes undefined, the default value
is used.
Syntax
function functionName(
parameter: string = "Default Value"
): void {
// Function statements
}
Example
function greetStudent(name: string = "Student"): void {
console.log("Welcome, " + name);
}
greetStudent();
greetStudent("Rahul");
Expected Output
Welcome, Student
Welcome, Rahul
Explanation
-
The default value of
nameis"Student". - The first call omits the argument, so the default value is used.
-
The second call provides
"Rahul", so that value is used instead.
4. Default Parameters with Numbers
Default parameters are useful when a function should use a standard numeric value unless another value is supplied.
Example
function calculatePrice(
price: number,
quantity: number = 1
): number {
return price * quantity;
}
console.log("Price:", calculatePrice(500));
console.log("Price:", calculatePrice(500, 3));
Expected Output
Price: 500
Price: 1500
Explanation
- The default quantity is 1.
-
calculatePrice(500)calculates 500 × 1. -
calculatePrice(500, 3)calculates 500 × 3.
5. Optional Parameters vs Default Parameters
| Optional Parameters | Default Parameters |
|---|---|
Declared using ?. |
Declared using = and a default value. |
| The argument can be omitted. | The argument can be omitted. |
| If omitted, the parameter value is undefined. | If omitted, the default value is used. |
course?: string |
course: string = "Java" |
| Useful when the value is genuinely optional. | Useful when a fallback value is required. |
6. Required and Optional Parameter Order
In a TypeScript function, optional parameters should normally appear after required parameters. A required parameter cannot follow an optional parameter in an ordinary parameter list.
Correct Example
function displayStudent(
name: string,
course?: string
): void {
console.log("Name:", name);
console.log("Course:", course ?? "Not selected");
}
displayStudent("Rahul");
displayStudent("Priya", "Python");
Expected Output
Name: Rahul
Course: Not selected
Name: Priya
Course: Python
Explanation
The required name parameter comes first.
The optional course parameter comes next.
The nullish coalescing operator ?? supplies
a fallback when the course value is null or undefined.
7. Practical Example: CIIT Course Details
Let's create a function that displays a student's name, course, and learning mode. The course is optional, and the learning mode has a default value.
Example
function displayCourseDetails(
studentName: string,
course?: string,
learningMode: string = "Offline"
): void {
console.log("Student:", studentName);
console.log("Course:", course ?? "Not selected");
console.log("Learning Mode:", learningMode);
}
displayCourseDetails("Priya");
displayCourseDetails("Rahul", "Dot Net Full Stack");
displayCourseDetails("Amit", "Java Full Stack", "Online");
Expected Output
Student: Priya
Course: Not selected
Learning Mode: Offline
Student: Rahul
Course: Dot Net Full Stack
Learning Mode: Offline
Student: Amit
Course: Java Full Stack
Learning Mode: Online
Explanation
-
studentNameis required. -
courseis optional. -
learningModedefaults to"Offline". - The third call provides all three values, so the supplied learning mode is used.
Common Mistakes
- Forgetting the question mark when declaring an optional parameter.
- Expecting an omitted optional parameter to automatically receive a custom default value.
- Placing a required parameter after an optional parameter in an ordinary parameter list.
- Confusing an optional parameter with a parameter that has a default value.
- Assuming that a default value replaces every supplied argument. It is used when the argument is omitted or is undefined.
? when an argument can be omitted
and = when a fallback value should be used.
Practice Task
Write TypeScript functions to complete the following tasks.
- Create a function that accepts a student's name and an optional course.
- Create a function with a default quantity of 1 and calculate the total price.
- Create a function that accepts a required product name and an optional price.
- Create a function with a default learning mode of "Offline".
- Create a function that combines required, optional, and default parameters.
Summary
In this lesson, we learned how to declare optional parameters using the question mark symbol and how to assign default values using the equals sign. We also compared both types, reviewed parameter ordering, and used them in a practical course details example.