Using ||
for default values
If you are coding in JavaScript for a while so you must be using ||
in many places, especially in conditionals.
But sometimes, we often use ||
to assign default values.
For example, sometimes, during some calculations, we might get null
(falsy value) from backend API but we don't want to show null
as such, we want to show 0
.
So, we might do something like this:
// Simulating a scenario where a backend API returns a null number
const returnedPriceFromAPI = null;
// Using the || operator to assign a default value if the returned number is falsy
const calculatedPrice = returnedPriceFromAPI || 0;
console.log(calculatedPrice) // 0
Similar example for strings can be given below:
// Simulating a scenario where a backend API returns a null string
const returnedNameFromAPI = null;
// Using the || operator to assign a default value if the returned name is falsy
const displayName = returnedNameFromAPI || "Anonymous";
console.log(displayName); // "Anonymous"
In this example, if returnedNameFromAPI is falsy (null in this case), we default to the string "Anonymous."
💡 This can be particularly handy when you want to ensure that you always have a meaningful value to work with, even if the API response is not as expected.
Should you always use ||
?
I would not advise that. Why?
Logical OR operator uses the right side value if the left side one is falsy and even though it works perfectly fine but we all know in JavaScript, undefined or null does not mean false so we have nullish operator specifically to deal with null and undefined so it is advised to use that instead and follow standard code practices.
In JavaScript, falsy does not mean undefined
or null
.
Look at this:
console.log(true || "shameel"); // true
console.log(false || "shameel"); // "shameel"
console.log(0 || "shameel"); // "shameel"
console.log(1 || "shameel"); // 1
console.log("uddin" || "shameel"); // "uddin"
console.log("" || "shameel"); // "shameel"
console.log(undefined || "shameel"); // "shameel"
console.log(null || "shameel"); // "shameel"
Using ??
for default values
nullish
strictly means null
or undefined
. Nothing else. It can be considered as a subset of falsy
.
So, if your intention is to use default values when something received is null
or undefined
ONLY then you must prefer ??
.
Lets look at this:
console.log(true ?? "shameel"); // true
console.log(false ?? "shameel"); // false
console.log(0 ?? "shameel"); // 0
console.log(1 ?? "shameel"); // 1
console.log("uddin" ?? "shameel"); // "uddin"
console.log("" ?? "shameel"); // ""
console.log(undefined ?? "shameel"); // "shameel"
console.log(null ?? "shameel"); // "shameel"
I hope the blog helps you in some way :)
Please let me know if any correction is required elsewhere or a better advice =)
Happy coding! 🎉💻✨
Follow me for more such content:
LinkedIn: https://www.linkedin.com/in/shameeluddin/
Github: https://github.com/Shameel123