Where Will We Go
— Lifestyle, JavaScript, Coding
"The real hidden features are the friends we made along the way." — Jane Manchun Wong
Defaulting values
1.) Use ??
- nullish coalescing operator to default values if the variable is undefined
or null
.
Example where dataSet
is an object.
const dataSet = {}
// destruct -> assign
const { expirationDate } = dataSet
console.log(expirationDate ?? "N/A")
For this example, the code above will return "N/A" because the expirationDate
is not defined.
2.) Use the ||
- OR operator to default values if the variable is defined but falsy.
Here's an example with a key of an object to compare is defined but falsy.
const dataSet = {
expirationDate: "", // <- defined
}
const { expirationDate } = dataSet
console.log(expirationDate || "N/A")
For this example, the code above will return "N/A" because the expirationDate
is falsy. It is falsy because it is declared as an empty string.
Check the complete list of falsy values in JavaScript at MDN.
Summary
??
- nullish coalescing returns the right side if the left value is eitherundefined
ornull
.||
- OR operator returns the right side if the left value is falsy.