The “or” (||
) operator and the “nullish coalescing operator” (??
) can be used in similar ways when reading a property from an object that may or may not exist. When dealing with strings you’re typically better off using “or” (||
) and for numbers you’re typically better off using the “nullish coalescing operator” (??
).
Possibly Missing Properties
If you read the property of an object that does not exist, the result is undefined
.
obj = { a: "hi" };
console.log(obj.z); // undefined
A Default Value
We can provide a default fallback value using ??
or ||
obj = { a: "hi" };
console.log(obj.a || "howdy"); // "hi"
console.log(obj.a ?? "howdy"); // "hi"
console.log(obj.z || "howdy"); // "howdy"
console.log(obj.z ?? "howdy"); // "howdy"
Different Behavior for falsy Values
When using ||
the fallback value is used if the property is any falsy
value.
When using ??
the fallback value is only used when the property is null
or undefined
.
Falsy Values
Each of the following are falsy values:
undefined
null
0
- empty string (
""
) NaN
These are the most common falsy values, see the full list of JavaScript falsy values.
Examples
Object | obj.a || "fallback" |
obj.a ?? "fallback" |
---|---|---|
obj = {} |
"fallback" |
"fallback" |
obj = { a: "hi" } |
"hi" |
"hi" |
obj = { a: "" } |
"fallback" |
"" |
obj = { a: 5 } |
5 |
5 |
obj = { a: 0 } |
"fallback" |
0 |
obj = {a: null} |
"fallback" |
"fallback" |
General Advice
When dealing with strings you’re typically better off using “or” (||
) and for numbers you’re typically better off using the “nullish coalescing operator” (??
).
In my experience, when working with strings you typically want the fallback value when the string is empty (""
) but when working with numbers you do not want the fallback value when the value is zero (0
). Since both empty string and zero are falsy
, I tend to use different operators depending on the type.
Disclaimer: This is general advice and ultimately the decision to use “or” (||
) or the “nullish coalescing operator” (??
) should come down to your particular use case.
Leave a Reply