3

I've see both x || [] and x ?? [] used for providing a fallback value if x is nullish. Are there any cases where these two give different results?

JOrielly
  • 31
  • 2
  • You can checkout this answer: https://stackoverflow.com/questions/61480993/when-should-i-use-nullish-coalescing-vs-logical-or/63924076#63924076 – Sanket Shah Aug 30 '21 at 04:19
  • `||` works in older browser and considers more things to be `false`. `??` is usually what you want =) – Evert Aug 30 '21 at 04:32
  • Does this answer your question? [When should I use ?? (nullish coalescing) vs || (logical OR)?](https://stackoverflow.com/questions/61480993/when-should-i-use-nullish-coalescing-vs-logical-or) – jonrsharpe Jul 31 '22 at 07:29

3 Answers3

2

If x was a non-nullish falsey value, it would be different.

x = 0;
x = x ?? []
console.log(x);



y = null;
y = y ?? []
console.log(y);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

These expressions x || [] and x ?? [] are logical assignments in Javascript.

x ?? [] is used to represent null or undefined cases while x || [] represent true if either a or b is true.

  • x ?? [] works by evaluating if the left side of the expression is null or undefined.

  • x || [] works by evaluating if a or b is true. If a is true continue in the if statement. If b is true, continue in the if statement.

yet-it-compiles
  • 108
  • 1
  • 10
0

They do different things.

?? is called Nullish coalescing operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

And works checking if the left side of the evaluation is null or undefined and if it's not the case will assign the right side of the evaluation.

The previous is really useful when you are checking a variable with the value zero which will be false if you are checking for it.

|| is the Logical Operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR

The logical operator works as any other logical operator. Will evaluate the left side and then the right side

null || 1 // output 1
undefined || 1 // output 1
0 || 1 // 1 <-- there are cases where you want to treat zero as a truthy value and **that's where the nullish operator is handy**
ncubica
  • 8,169
  • 9
  • 54
  • 72
  • 1
    `0 || 1` returns 1, so perhaps you meant that the *desired* result is 0, but that's not clear from the comments. ;-) – RobG Aug 30 '21 at 03:50
  • yeah that was what I want to say... will update the comment :pray: – ncubica Aug 30 '21 at 03:52