Default parameters is a feature in JavaScript that allow function parameters to be initialized with a default value if no argument is given for that parameter, or if a value of undefined
is assigned to that function parameter.
Default parameters are set using the assignment operator =
, with the default value being on the right side of the assignment operator.
The syntax looks something like this:
parameter = defaultValue
This feature can only be used for function parameters and when destructuring values from an array or object.
Default parameters only work for variables that have the type of undefined
, whether assigned implicitly or explicitly.
// Implicit assignment
let valueOne;
console.log(typeof valueOne);
// returns 'undefined'
// Explicit assignment
const valueTwo = undefined;
console.log(typeof valueTwo);
// returns 'undefined'
A variable declared without any assigned value will have a default value of undefined
- implicit assignment.
// Default parameters are used only when:
typeof value === 'undefined'
// returns true
The default parameter value will not be used if a variable has a falsy value other than undefined
. Other falsy values such as empty strings, null
, false
or 0
will replace the default parameter value.
const greetUser = (name = 'stranger') => {
console.log(`Welcome ${name}!`);
};
greetUser('Danielle');
// Welcome Danielle!
greetUser();
// Welcome stranger!
Using Destructuring Assignment
Default parameters also work quite well with destructuring assignment, and when combined can produce clean, concise code.
With Arrays
Let's assume we have an array of numbers. If we want to provide a default value for the second element in the array, here is how it would be done:
let [firstNumber, secondNumber = 22] = [63];
console.log(firstNumber);
// 63
console.log(secondNumber);
// 22
To provide a default value for the first element in the array:
let [firstNumber = 71, secondNumber] = [, 63];
console.log(firstNumber);
// 71
console.log(secondNumber);
// 63
With Objects
Providing a default value for the properties of a destructured object is almost the same with the example above that used array destructuring.
The difference here, is that we assign the default value to the property destructured from the object.
const userDetails = {
profession: 'developer',
location: 'Nigeria'
};
const { name = 'Ayo', profession, location } = userDetails;
console.log(name);
// 'Ayo'
console.log(profession);
// 'developer'
console.log(location);
// 'Nigeria'
When expecting an object as a function parameter, if we know the properties of that object, we can destructure the properties we need from the object and assign default parameter values to them also.
const printUserDetails = ({ name = 'Ayo', location }) => {
console.log(`I'm ${name}, based in ${location}.`);
};
printUserDetails(userDetails);
// "I'm Ayo, based in Nigeria."
Thanks for reading.๐
Feel free to react and leave a comment.๐ฏ