Can you add booleans in JS? Is something false
here? What will be logged to the screen?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Just as in the previous test, we’re dealing here with type conversion
and loose equality
using the ==
operator.
When JavaScript evaluates the expression true + true
it first converts booleans to numbers, which is 1
for true
and 0
for false
.
When we try to do calculate the value of 2 == true
, the typecast happens again and we arrive at the final condition 2 == 1
.
The result is obviously false, so we go into the else
branch.
To understand how type conversion works with the +
operator and different data types, you can read this article.
ANSWER: the string everyone is different after all
will be logged to the console.
Top comments (8)
You can use this property of booleans to implement an exclusive or:
Or count things cleanly...
Now I think about it,
filter
withlength
would be simpler in both casesA hell of a lot cleaner, in theory a bit slower too.
filter
allocates, fills and returns an array, which we're then instantly throwing away after getting its length.reduce
functions more like afor
loop, iterating over each element and accumulating a sum.That's in theory though. JS performance is fickle thing, and on perf.link it seems your
filter
method is both cleaner looking, and faster for arrays with fewer than 10000 items.Perf.link link
Go figure! Good to know
What we really want is something like ruby's
count
, which only returns the filtered size...😎
That's clever. Thank you!
Has anyone ever actually come across an instance where they have to sum two booleans?
To pre-empt, xor is not the result of summing booleans.
Not two booleans, but a standard for a sort handler I use is:
(albeit
a
andb
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 afterb
. 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.
Smart way of sorting, that's really taking advantage of how JS works. Can't do that in strongly typed languages.