DEV Community

Discussion on: JavaScript's unsafe optional chaining is crazy |:

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

~ is a bitwise NOT operator - flipping all the bits in a number. Flipping them twice gets you back to the original number. Using it with undefined (what you'll get from the optional chain if order is missing) or any falsy value - is the same as using it with 0

I am making the presumption here that order will be an integer. The solution I suggest will also remove the decimal part from any order value

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Presumably you are using optional chaining here as you are expecting a or b to possibly be undefined or null? If this is not the case, you don't even need optional chaining and could simply use:

 const sortComparer = (a, b) => ~~a.order - ~~b.order
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
mnathani profile image
Murtaza Nathani

Hey Jon, yes I am assuming the values to null or undefined, and that's the reason why I am using optional changing..

However, using your approach wouldn't ~~undefinded break the code ? 🤔

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

As I said, ~~undefined gives 0

Thread Thread
 
mnathani profile image
Murtaza Nathani

umm, interesting way.. never used it though, however not sure if this is the best practise or not..

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

Best practises should always be challenged and questioned

Thread Thread
 
mnathani profile image
Murtaza Nathani

Agreed, there's always more then one to do the stuff, whatever works best !