40

What is the difference between ?? and || in JS

const a = {}

const b = a.name ?? 'varun 1'

console.log(b)

const d = a.name || 'varun 2'

console.log(d)

In the above code they both work the same. I know || is OR i.e if the first statement is false then set the value for the next one. Is it same for ???

Ergwun
  • 12,579
  • 7
  • 56
  • 83
Cyberduck
  • 571
  • 3
  • 6
  • 12

2 Answers2

77

The main difference is that nullish coalescing(??) operator will only give the result as the right operand only if the left operand is either null or undefined.

Whereas the OR(||) operator will give the result as right operand for all the falsy values of the left operand.

Below are some examples

  • Snippet 1: With 0 as input

const a = 0;
// a || 10 --> Will result in 10, as || operator considers 0 as falsy value and resulting the right side operand
console.log(`a || 10 = ${a || 10}`);
// a ?? 10 --> Will result in 0, as ?? operator considers 0 as truthy value and resulting the left side operand
console.log(`a ?? 10 = ${a ?? 10}`);
  • Snippet 2: With '' as input

const a = ''
console.log(`a || "ABC" = ${a || "ABC"}`); // ABC
console.log(`a ?? "ABC" = ${a ?? "ABC"}`); // ''
  • Snippet 3: With null as input

const a = null;
console.log(`a || 10 = ${a || 10}`); // 10
console.log(`a ?? 10 = ${a ?? 10}`); // 10
  • Snippet 4: With undefined as input

const a = {}
// Here a.name will be undefined, hence both of the operands results the right side operand
console.log(`a.name ?? 'varun 1' = ${a.name ?? 'varun 1'}`); // 'varun 1'
console.log(`a.name || 'varun 2' = ${a.name || 'varun 2'}`); // 'varun 2'

const a = {name: ''}
// Here a.name will be '', then

// ?? will result ''
console.log(`a.name ?? 'varun 1' = ${a.name ?? 'varun 1'}`);
// || will result in 'varun 2'
console.log(`a.name || 'varun 2' = ${a.name || 'varun 2'}`);
  • Snippet 5: With false as input

const a = false;
console.log(`a || 10 = ${a || 10}`); // 10
console.log(`a ?? 10 = ${a ?? 10}`); // false

As mentioned above, both the operators behave similarly when the input is either null or undefined. The real difference we'll get to see when we provide falsy values such as 0, '', false, NaN.

Nithish
  • 5,393
  • 2
  • 9
  • 24
  • The main difference between ?? and || is how they handle falsy values. ?? only considers null and undefined as nullish, while || considers any falsy value as potentially false. In summary, use the nullish coalescing operator ?? when you specifically want to handle null or undefined and use the logical OR operator || when you want to handle any falsy value (including null and undefined). – Chidiebere Ezeokwelume Aug 04 '23 at 15:42
4

You can see a difference in

const a = ''

const b = a ?? 'varun 1'

console.log(b)

const d = a || 'varun 2'

console.log(d)

because a ?? 'varun 1' returns 'varun 1' only if a is null or undefined but a || 'varun 2' returns 'varun 2' if a is falsy. Some falsy values are empty strings, zero and boolean false.