2

I was going through the new proposed functionalities in ES2020 and I stumbled upon the ?? operator also known as the “nullish coalescing operator”.

The explanation was vague and I still don't get how it is different from the logical OR operator (||)

Ry-
  • 218,210
  • 55
  • 464
  • 476
Saksham
  • 9,037
  • 7
  • 45
  • 73
  • 1
    You can find explanation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator – Ray Jan 24 '20 at 06:54
  • 4
    Use `||` is when you want to check if the expression is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) (0, `''`, false, null, undefined, NaN). Use `??` when you want to check if it null or undefined – adiga Jan 24 '20 at 06:56
  • [Is there a “null coalescing” operator in JavaScript?](https://stackoverflow.com/questions/476436) – adiga Jan 24 '20 at 07:03

1 Answers1

3

Explanation is very simple lets assume that we have next situation, we want to get a value if it exist in object or use other value if it's undefined or null

const obj = { a: 0 }; 
const a = obj.a || 10; // gives us 10

// if we will use ?? operator situation will be different
const obj = { a: 0 };
const a = obj.a ?? 10; // gives us 0

// you can achieve this using this way
const obj = { a: 0 };
const a = obj.a === undefined ? 10 : obj.a; // gives us 0

// it also work in case of null
const obj = { a: 0, b: null };
const b = obj.b ?? 10; // gives us 10

Basically this operator does next:

// I assume that we have value and different_value variables
const a = (value === null || value === undefined) ? different_value : value;

More information about this you can find in MDN web docs

alex2007v
  • 1,230
  • 8
  • 12