0

What is the difference in this instance between using the optional chaining with nullish coalescing and or operator when the value it's undefined? the both seem to be working alike.

Which one it's prefered and why?

const api = {
  entry: undefined
}


const obj_nullish = {
  foo: api?.entry ?? 'Not found'
}

const obj_or = {
  foo: api.entry || 'Not found'
}

console.log(obj_nullish)
console.log(obj_or)
Álvaro
  • 2,255
  • 1
  • 22
  • 48

1 Answers1

1

The main difference is that null coalescing checks left hand value explicitly against undefined or null (nullish)

The || logical operator checks left hand side falseness

Example:

const nullCoalescing = "" ?? "right" // nullCoalescing is ""
const logicalOr = "" || "right"      // logicalOr is "right"

console.log(`null coalescing: ${nullCoalescing}`);
console.log(`logical or: ${logicalOr}`);

Source: Nullish Coalescing vs OR