Considering `??` vs `||`
Alex Lohr

Alex Lohr @lexlohr

About: ...former musician, voice actor, martial artist, started coding 38 years ago and turned front-end developer 25+ years ago.

Location:
Germany
Joined:
Jun 13, 2017

Considering `??` vs `||`

Publish Date: Apr 22 '20
9 4

The nullish coalescing operator ?? will result in the left expression unless that contains null or undefined - in that case the right expression is used. It mainly resolves the issues of the logical or operator || in combination with the conversion into boolean of falsy values like zero or empty strings.

It should therefore be a no-brainer to just replace all || with ?? - or is it?

Consider the following code snippet:

item[kind] || null
Enter fullscreen mode Exit fullscreen mode

This would usually be a prime example for the nullish coalescing operator, were it not for the fact that the right expression of the or operator is null.

Now imagine this example in the context of a react application, where the number zero or an empty string, which are both falsy, are rendered as text node. Had we used the nullish coalescing operator instead, it would result in unwanted nodes being rendered, in the case of the number zero even visible ones.

Values may be coerced on purpose and using the nullish coalescing operator without prior consideration could therefore cause a regression.

TL;DR: if the right value of or/nullish coalescing operator ||/?? is null or undefined, take a closer look if the effects of type coercion could be intended. Otherwise, using ?? instead of || will make your code more predictable.

Comments 4 total

  • Pacharapol Withayasakpunt
    Pacharapol WithayasakpuntDec 16, 2020

    Falsiness and || are sins in JavaScript. Carelessness can lead to unexpected.

    ?? is OK, but you have to be careful that BOTH null and undefined are considered. Please read the specification carefully.

    ?. is so bad that it doesn't work with

    • Array get index nullability
    • Followed by function
    let x
    x?.run()  // undefined
    x?.run?()  // Uncaught SyntaxError
    
    Enter fullscreen mode Exit fullscreen mode
    • Alex Lohr
      Alex LohrDec 17, 2020

      I wouldn't go so far to call them sins, but I agree that you can easily be careless in this language. JavaScript is not the only weak typed language, though (take Lua or Python for example). Also, || still has its merits where you consciously want to catch all falsy values.

    • Alex Lohr
      Alex LohrMay 6, 2021

      Also your syntax error is actually that, because the correct code would be

      let x
      x?.run() // undefined
      x?.run?.() // undefined
      
      Enter fullscreen mode Exit fullscreen mode
    • Philipp Mudra
      Philipp MudraJun 3, 2021
      • Array get index nullability

      For the sake of completeness this is also supported:

      let x
      x?.[0] // undefined
      
      Enter fullscreen mode Exit fullscreen mode
Add comment