r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

150

u/Loves_Poetry Mar 18 '19
array.every(Number.isFinite)

Because it's plain english.

46

u/dmethvin Mar 19 '19

Also very poetic, so I can see why you like it.

19

u/ahartzog Mar 19 '19

TIL about array.every. Awesome tool, thanks!

11

u/Satoshi_Hodler Mar 19 '19

There's a small caveat that it always returns true on empty arrays, which might be not what you need.

27

u/Tysonzero Mar 19 '19

That's the mathematically correct thing to do, it's actually a pretty fundamental mathematical principle. Vacuous truth

1

u/NoInkling Mar 19 '19

Right, it doesn't make the method "weird", but it is something you have to keep in mind regardless because you could intuit both ways.

1

u/third774 Mar 19 '19

Is there a similar term for .some() always returning false on empty arrays? I suppose it's still "vacuous", right? So maybe "Vacuous Falsity"?

7

u/NoInkling Mar 19 '19 edited Mar 19 '19

If it's not, you can do:

array.length && array.every(Number.isFinite)

// If it must evaluate to a boolean:
!!array.length && array.every(Number.isFinite)
// or
array.length > 0 && array.every(Number.isFinite)

1

u/[deleted] Mar 19 '19

Also note the counterpart, Array.prototype.some. Returns true if one or more items match the condition.

const arr = [1, 2, 3];

arr.some(n => n > 2) // true

arr.some(n => n < 0) // false

1

u/ahartzog Mar 19 '19

Good to know there’s a native version of this; I’ve usually just grabbed it from Lodash

8

u/Tysonzero Mar 19 '19

You'd love Haskell:

all (> 5) array
-- all (> 5) [4, 5, 6]
-- False

for array print
-- for [1, 2, 3] print
-- 1
-- 2
-- 3

takeWhile (any (< 3)) arrayOfArrays
-- takeWhile (any (< 3)) [[1, 2], [3, 4], [2, 3]]
-- [[1, 2]]

1

u/FormerGameDev Mar 25 '19

... what would you use this for?

1

u/NoInkling Mar 19 '19

Ruby (considered a pretty "English-readable" language) for comparison:

array.all?(&:finite?)
# Or if you prefer:
array.all? { |number| number.finite? }