JavaScript Default Parameters
JavaScript functions allow you to define default values for parameters. This feature, introduced in ES6 (ECMAScript 2015), helps prevent bugs when parameters are not provided and ensures that functions behave as expected. Default parameters provide a way to specify initial values for function arguments, making code more robust and reducing the need for manual checks.
A default parameter is a way to assign a default value to a function parameter if no value or undefined
is passed to the function. This helps ensure that a parameter always has a value, making your functions more predictable and reducing the need for conditional checks inside the function body.
The basic syntax for default parameters is:
function functionName(parameter = defaultValue) {
// function body
}
undefined
is passed when calling the function.Let’s look at a basic example to understand how default parameters work.
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet('Alice'); // Output: Hello, Alice!
greet(); // Output: Hello, Guest!
In this example:
greet('Alice')
, the value 'Alice'
is passed and used as the argument.greet()
with no argument, the default value 'Guest'
is used.Default parameters improve the readability and maintainability of code by reducing the need for additional conditional statements or manual checks for undefined
values. Without default parameters, you might have to write code like this:
function greet(name) {
if (name === undefined) {
name = 'Guest';
}
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
greet('Bob'); // Output: Hello, Bob!
As you can see, default parameters eliminate the need for the if
check, making the code cleaner and easier to understand.
You can also use default parameters when your function has multiple parameters. Each parameter can have its own default value, making it flexible for different use cases.
function createProfile(name = 'Anonymous', age = 18, country = 'Unknown') {
console.log(`Name: ${name}, Age: ${age}, Country: ${country}`);
}
createProfile(); // Output: Name: Anonymous, Age: 18, Country: Unknown
createProfile('John', 30); // Output: Name: John, Age: 30, Country: Unknown
createProfile('Alice', 25, 'USA'); // Output: Name: Alice, Age: 25, Country: USA
In this example:
undefined
It's important to note that default parameters only kick in when undefined
is passed or no value is passed at all. If a function argument is explicitly passed as null
, it will not trigger the default value.
null
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(null); // Output: Hello, null!
greet(); // Output: Hello, Guest!
In this example, when null
is passed, the function uses null
as the value instead of the default value 'Guest'
. Default parameters only apply when the value is undefined
, not when it's explicitly set to null
.
You can also use expressions as default values. This allows for more dynamic defaults based on conditions, calculations, or function calls.
function calculateTotal(price, tax = price * 0.05) {
console.log(`Total Price: $${price + tax}`);
}
calculateTotal(100); // Output: Total Price: $105
calculateTotal(100, 20); // Output: Total Price: $120
In this example:
tax
parameter is not passed, it defaults to 5%
of the price
.tax
is passed, the default is overridden.Default parameters can also be used with object or array destructuring, allowing you to set default values for destructured variables.
function displayPerson({ name = 'John Doe', age = 30 }) {
console.log(`Name: ${name}, Age: ${age}`);
}
displayPerson({}); // Output: Name: John Doe, Age: 30
displayPerson({ name: 'Alice' }); // Output: Name: Alice, Age: 30
In this example:
name
or age
properties are missing from the object, the default values are used.Arrow functions, just like traditional functions, also support default parameters. The syntax remains the same.
const multiply = (a, b = 2) => a * b;
console.log(multiply(3)); // Output: 6 (3 * 2)
console.log(multiply(3, 4)); // Output: 12 (3 * 4)
Here, the b
parameter has a default value of 2
. If only one argument is passed, the second argument defaults to 2
.
JavaScript allows you to combine default parameters with rest parameters to create flexible and powerful functions.
function sum(base, ...numbers) {
const total = numbers.reduce((acc, num) => acc + num, base);
return total;
}
console.log(sum(10, 1, 2, 3)); // Output: 16 (10 + 1 + 2 + 3)
console.log(sum(10)); // Output: 10 (just the base value)
In this example:
base
parameter has no default value, but the numbers
parameter uses rest parameters to collect any remaining arguments.base
is handled by adding additional logic in the function.