DEV Community

Discussion on: Considering `??` vs `||`

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

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
Collapse
 
lexlohr profile image
Alex Lohr

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.

Collapse
 
lexlohr profile image
Alex Lohr

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
Collapse
 
pmudra profile image
Philipp Mudra
  • Array get index nullability

For the sake of completeness this is also supported:

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