Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nullish coalescing vs logical OR operator

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading