Have you came across like this situation ?
obj.name ? obj.name : "I don't know"
If you so, better write code like that
obj.name || "I don't know"
||
is called Locgical OR. When left-hand is undefined
or null
returns right-hand
🤔 Is it the same as
??
??
is called Nullish coalescing operator, it's like Logical OR except falsy values like ""
, 0
// example
const obj = {
zero: 0,
one: 1,
emptyString: '',
null: null,
undefined: undefined,
}
console.log(obj.zero || 'Hello')// Hello
⭐ console.log(obj.zero ?? 'Hello')// 0
console.log(obj.one || 'Hello')// 1
console.log(obj.one ?? 'Hello')// 1
console.log(obj.emptyString || 'Hello')// Hello
⭐ console.log(obj.emptyString ?? 'Hello')// ""
console.log(obj.null || 'Hello')// Hello
console.log(obj.null ?? 'Hello')// Hello
console.log(obj.undefined || 'Hello')// Hello
console.log(obj.undefined ?? 'Hello')// Hello
So the reason why I wrote you should use ||
is that normally you just need to recognise "undefined" or "null" in that case, not falsy value.
it's just my opinion and of course it depends on situation!
Top comments (0)