r/javascript • • Mar 18 '19

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

385 Upvotes

422 comments sorted by

View all comments

1

u/dai-shi Mar 19 '19

const iota = n => [...Array(n).keys()]

2

u/Shaper_pmp Mar 19 '19

I never understand why people feel the need to populate an array with a sequence of consecutive values. I've spent over 20 years writing javascript and never once encountered a legitimate use-case for doing it.

The only reason I can imagine is if someone wanted to "iterate X times" and was allergic to the simple for loop, so instead they're defining, reserving and populating an entire array in memory just so they can iterate over its array indices and then immediately throw it all away again... but that's pants-on-head crazy code.

Genuinely curious, in case I'm missing something...

1

u/dai-shi Mar 19 '19

I'd agree that we should avoid allocating memory if we could. I too don't use this form in production code. It's better to use just an iterator `Array(n).keys()` not an allocated array.

The only reason I'd require an array is when the function I call doesn't accept an iterator but only an array. I often use array.map, and it's handy to have an allocated array, mostly for tooling not production code.

iota usually take the second and third arguments, and without it, the usage is limited.

→ More replies (3)