Default parameters in JavaScript allow developers to assign default values to function parameters when no argument is provided or when the corresponding argument is explicitly undefined. Introduced in ECMAScript 2015 (ES6), this feature makes functions more flexible and helps prevent unexpected results caused by missing inputs. Default parameters are commonly used in calculations, user settings, configuration options, and reusable functions where certain values should be available automatically.
Table of Contents
What Are Default Parameters in JavaScript?
Default parameters are values assigned to function parameters in the function definition. When a function is called without providing a value for a parameter, JavaScript uses the specified default value if the argument is omitted or evaluates to undefined.
Before default parameters were introduced in ES6, developers often used conditional statements or the logical OR operator to provide fallback values. Default parameters offer a more direct and readable way to handle these situations.
Example:
// JavaScript program to demonstrate default parameters
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
greet("Tanavi");
greet();
Output:
Hello, Tanavi!
Hello, Guest!
Explanation:
The function greet() has a parameter named name with a default value of "Guest". When "Tanavi" is passed, the function uses that value. When the function is called without an argument, JavaScript uses "Guest" automatically.
Syntax of Default Parameters
The basic syntax of a default parameter is shown below.
function functionName(parameter = defaultValue) { /* function body */ }
In this syntax:
-
functionName represents the name of the function.
-
parameter is the variable that receives the argument.
-
defaultValue is the value used when the argument is omitted or evaluates to undefined.
-
The function body contains the statements that execute when the function is called.
Default parameters can be used in function declarations, function expressions, and arrow functions.
How Default Parameters Work
Default parameters are evaluated when a function is called. JavaScript checks each parameter to determine whether its corresponding argument is missing or has the value undefined. If either condition applies, the default value is used.
The process works as follows:
- Define a function with one or more parameters.
- Assign default values to the parameters that need them.
- Call the function with the required arguments.
- JavaScript uses the supplied values wherever they are provided.
- For omitted arguments or arguments evaluating to undefined, JavaScript uses the corresponding default values.
Default values are not used automatically for every falsy value. Values such as 0, false, an empty string, and null are preserved.
Simple Example of Default Parameters
The following example demonstrates how a default parameter works when an argument is provided and when it is omitted.
Example:
// JavaScript program to demonstrate a simple default parameter
function welcome(name = "Visitor") {
console.log("Welcome, " + name + "!");
}
welcome("Tanavi");
welcome();
Output:
Welcome, Tanavi!
Welcome, Visitor!
Explanation:
The function welcome() accepts a parameter named name. Its default value is "Visitor". The first function call provides "Tanavi", so that value is used. The second call does not provide an argument, so JavaScript uses the default value.
Default Parameters with Multiple Arguments
JavaScript functions can have multiple parameters, and each parameter can have its own default value. This allows a function to work correctly even when some arguments are omitted.
Example:
// JavaScript program to demonstrate multiple default parameters
function calculateTotal(price = 100, quantity = 1) {
return price * quantity;
}
console.log(calculateTotal());
console.log(calculateTotal(200));
console.log(calculateTotal(200, 3));
Output:
100
200
600
Explanation:
The function calculateTotal() has two parameters: price and quantity. Their default values are 100 and 1, respectively. When no arguments are supplied, the function calculates 100 × 1. When only price is supplied, quantity remains at its default value. When both arguments are supplied, the function uses both provided values.
Default Parameters with Undefined Values
A default parameter is used when the corresponding argument is omitted or explicitly evaluates to undefined. This behavior allows developers to use default values even when an undefined value is passed deliberately.
Example:
// JavaScript program to demonstrate undefined with default parameters
function displayMessage(message = "Default message") {
console.log(message);
}
displayMessage("Hello!");
displayMessage(undefined);
displayMessage();
Output:
Hello!
Default message
Default message
Explanation:
When "Hello!" is passed, the function prints the supplied string. When undefined is passed explicitly or the argument is omitted, JavaScript uses "Default message". This behavior makes default parameters useful for handling missing inputs.
Default Parameters vs Null Values
Default parameters are applied when an argument is omitted or evaluates to undefined. However, passing null does not activate the default value because null is an explicitly supplied value.
Example:
// JavaScript program to compare undefined and null with default parameters
function showValue(value = "Default value") {
console.log(value);
}
showValue(undefined);
showValue(null);
showValue("");
showValue(0);
Output:
Default value
null
0
Explanation:
The first call uses the default because the argument is undefined. The second call prints null, and the third prints an empty string. The fourth prints 0. These values are not replaced by the default parameter because they are explicitly supplied and are not undefined.
Default Parameters with Expressions
Default parameter values can contain expressions, calculations, or function calls. These expressions are evaluated when the function is called, and the default value is needed.
Example:
// JavaScript program to demonstrate expressions in default parameters
function calculateArea(length = 5, width = length * 2) {
return length * width;
}
console.log(calculateArea());
console.log(calculateArea(4));
console.log(calculateArea(4, 3));
Output:
50
32
12
Explanation:
The parameter length has a default value of 5, while width defaults to twice the value of length. When no arguments are supplied, the area is 5 × 10, which equals 50. When only length is set to 4, the default width becomes 8, producing 32. When both arguments are supplied, the function uses those values directly.
Default Parameters with Earlier Parameters
A default parameter can refer to a parameter declared before it in the same parameter list. This is useful when one default value depends on another parameter.
Example:
// JavaScript program to demonstrate dependent default parameters
function introduce(name, message = "Hello, " + name) {
console.log(message);
}
introduce("Tanavi");
introduce("Tanavi", "Welcome to JavaScript!");
Output:
Hello, Tanavi
Welcome to JavaScript!
Explanation:
The default value of message uses the earlier parameter name. When the second argument is omitted, JavaScript creates a greeting using the supplied name. When a message is explicitly provided, the function uses that message instead.
A default parameter generally cannot access a later parameter in the same parameter list because that later parameter has not yet been initialized.
Default Parameters with Arrow Functions
Default parameters can also be used with arrow functions. The syntax is similar to that of regular functions, and the default value is applied when the argument is omitted or evaluates to undefined.
Example:
// JavaScript program to demonstrate default parameters with an arrow function
const greet = (name = "Guest") => {
console.log("Hello, " + name + "!");
};
greet("Tanavi");
greet();
Output:
Hello, Tanavi!
Hello, Guest!
Explanation:
The arrow function greet defines name with a default value of "Guest". The first call uses the supplied name, while the second call uses the default. Default parameters work with arrow functions in the same way as with regular functions.
Default Parameters vs the Logical OR Operator
Before ES6, developers often used the logical OR operator (||) to provide fallback values. However, || uses the fallback whenever the left-hand value is falsy, whereas default parameters only use their fallback when the argument is omitted or evaluates to undefined.
Example:
// JavaScript program to compare default parameters with the logical OR operator
function usingDefault(value = 10) {
return value;
}
function usingOr(value) {
return value || 10;
}
console.log(usingDefault(0));
console.log(usingOr(0));
console.log(usingDefault(""));
console.log(usingOr(""));
Output:
0
10
10
Explanation:
The default parameter preserves 0 and the empty string because both are explicitly supplied values. The logical OR operator replaces them with 10 because both are falsy. Default parameters are generally a better choice when the fallback should apply only to missing or undefined values.
Advantages of Default Parameters
Default parameters provide several benefits when writing JavaScript functions.
- Simpler code: They reduce the need for extra conditional statements to handle missing arguments.
- Improved readability: Default values are visible directly in the function definition.
- Reliable behavior: They help prevent missing arguments from unintentionally producing undefined in calculations or messages.
- Flexible functions: A function can accept optional arguments without requiring every argument to be supplied.
- Support for expressions: Default values can depend on earlier parameters or be calculated when needed.
- Compatibility with modern functions: They work with function declarations, function expressions, and arrow functions.
Common Beginner Mistakes
- Assuming defaults apply to every falsy value: Default parameters apply when an argument is omitted or evaluates to undefined. Values such as 0, false, null, and an empty string do not trigger the default.
- Confusing null with undefined: Passing null does not activate a default parameter because null is an explicit value.
- Placing dependent parameters in the wrong order: A default parameter can refer to an earlier parameter, but it cannot directly access a later parameter that has not yet been initialized.
- Thinking default values are evaluated when the function is defined: Default expressions are evaluated when the function is called, and the corresponding default is needed.
- Using || when zero or an empty string is valid: The logical OR operator replaces all falsy values, while default parameters preserve explicitly supplied values other than undefined.
Conclusion
Default parameters in JavaScript provide a convenient way to assign fallback values to function parameters. They make functions easier to read, reduce unnecessary conditional logic, and allow functions to handle optional inputs more reliably. By understanding how default parameters behave with undefined, null, expressions, and multiple arguments, developers can create more flexible and maintainable JavaScript programs.
FAQs
1. What are default parameters in JavaScript?
Default parameters allow developers to assign fallback values to function parameters when an argument is omitted or evaluates to undefined.
2. When are default parameters used?
Default parameters are used when the corresponding argument is not provided or is explicitly undefined. Otherwise, JavaScript uses the supplied argument.
3. Do default parameters work with arrow functions?
Yes. Default parameters work with arrow functions, function expressions, and function declarations.
4. What is the difference between undefined and null in default parameters?
An omitted argument or undefined activates the default value, while null is treated as an explicitly supplied value and does not activate the default.
5. What is the difference between default parameters and the logical OR operator?
Default parameters use their fallback only when an argument is omitted or evaluates to undefined. The logical OR operator uses its fallback for any falsy value, including 0, false, and an empty string.
0 Comments