DEV Community


Discussion on: JavaScript Interview Question #18: What's the sum of two booleans in JavaScript?

andrewbridge profile image
Andrew Bridge

Not two booleans, but a standard for a sort handler I use is:

.sort((a, b) => {
   if (a === b) return 0;
   return ((a < b) * 2) - 1;
Enter fullscreen mode Exit fullscreen mode

(albeit a and b are often objects I'm pulling comparable values out of)

The sort result either needs to be below 0 or above 0 depending on whether a is before or after b. The nested boolean becomes a 0 or a 1, multiplied by 2 it's either 0 or 2, so subtracting 1 will given a final -1 or +1 result, which is exactly to the .sort spec.

There are also various code golf type tricks that boolean can use boolean maths in some way, but it's otherwise not that useful.

jmitchell38488 profile image
Justin Mitchell

Smart way of sorting, that's really taking advantage of how JS works. Can't do that in strongly typed languages.