DEV Community

Kaziu
Kaziu

Posted on

Difference between Logical OR (||) and Nullish coalescing operator(??)

Have you came across like this situation ?

obj.name ? obj.name : "I don't know"
Enter fullscreen mode Exit fullscreen mode

If you so, better write code like that

obj.name || "I don't know"
Enter fullscreen mode Exit fullscreen mode

|| 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
Enter fullscreen mode Exit fullscreen mode

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)