3 Ways to set default values
1. Variables
The nullish coalescing operator (??
) is a logical operator that returns its right-hand side operand when its left-hand side operand is null
or undefined
and otherwise returns its left-hand side operand. We can use this to set default values, for example when we receive a list that has not been set to an array yet:
const bookList = receivedBooks ?? [];
2. Parameters
We could use the null coalescing operator to set defaults for variables in functions but there is a better way, default parameters:
function calculateArea(width, height = 100) {
return width * height;
}
const area = calculateArea(50);
console.log(area); // 5000
3. Objects
We can also give default value once we destructure object properties. ES6 destructuring default values only kick in if the value is undefined
.
const rectangle = { height: 400 };
const { height = 750, width = 500 } = rectangle;
console.log(height); // 400 - comes from rectangle object
console.log(width); // 500 - fallback to default