Default Parameter Values
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 26 of 73.
While optional parameters let you choose whether to provide a value, default parameters take this concept further by automatically providing a fallback value when no argument is passed. This makes functions more convenient to use while maintaining type safety.
To create a default parameter, you assign a value directly in the function signature using the equals sign. TypeScript automatically infers the parameter's type from the default value:
function greet(name: string, greeting = "Hello"): string {
return greeting + ", " + name;
}
function calculateArea(width: number, height = 10): number {
return width * height;
}In these examples, greeting defaults to "Hello" (inferred as string) and height defaults to 10 (inferred as number). When you call greet("Alice"), it automatically uses the default greeting, but you can still override it with greet("Alice", "Good morning").
Default parameters are effectively optional - you don't need to use the ? syntax because the default value ensures the parameter always has a value. This approach is cleaner than optional parameters when you have a sensible default, as it eliminates the need to check for undefined inside your function.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a function named calculateTax that takes two parameters: price of type number (required) and rate of type number with a default value of 0.05. The function should return the tax amount as a number with an explicit return type annotation.
The function should calculate the tax by multiplying the price by the rate.
Create another function named formatGreeting that takes two parameters: name of type string (required) and timeOfDay of type string with a default value of "Hello". The function should return a formatted greeting string with an explicit return type annotation.
The function should return the greeting in the format: "[timeOfDay], [name]!"
Create a third function named calculateShipping that takes three parameters: weight of type number (required), distance of type number (required), and expedited of type boolean with a default value of false. The function should return the shipping cost as a number with an explicit return type annotation.
The function should calculate shipping cost using this formula: (weight * 0.5) + (distance * 0.1). If expedited is true, multiply the result by 2.
Test your functions by calling them with the following values and printing the results:
- Call
calculateTaxwith100(using default rate) - Call
calculateTaxwith200and0.08 - Call
formatGreetingwith"Alice"(using default time of day) - Call
formatGreetingwith"Bob"and"Good morning" - Call
calculateShippingwith5and100(using default expedited value) - Call
calculateShippingwith3,50, andtrue
Print each result on a separate line in the order specified above.
Cheat sheet
Default parameters provide fallback values when no argument is passed, making functions more convenient while maintaining type safety.
Create default parameters by assigning a value in the function signature using the equals sign. TypeScript automatically infers the parameter's type from the default value:
function greet(name: string, greeting = "Hello"): string {
return greeting + ", " + name;
}
function calculateArea(width: number, height = 10): number {
return width * height;
}Default parameters are effectively optional - you don't need the ? syntax because the default value ensures the parameter always has a value. This eliminates the need to check for undefined inside your function.
Try it yourself
// TODO: Write your code here
// Create the calculateTax function
// Create the formatGreeting function
// Create the calculateShipping function
// Test the functions and print resultsThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples