DEV Community

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

willsmart profile image
willsmart • Edited on

A 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 a for 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...

isEven = -> (v) { (v&1)==0 }
[1,2,3,4,5,6,7].count(&isEven) # <- 3
Enter fullscreen mode Exit fullscreen mode

😎