Array.from has a second argument
- Published at
- Updated at
- Reading time
- 1min
This post is part of my Today I learned series in which I share all my web development learnings.
This post is a rather quick one. I followed a Twitter conversation by Surma from Google and Andrea Giammarchi in which Andrea mentionied that Array
accepts a second argument. I heard this fact a few times before but always forgot it again. Let's hope I'll remember this fact the next time I want to create and transform an Array out of something.
console.log(Array.from([1, 2, 3], x => x + x));
// [2, 4, 6]
The snippet they discussed showed functionality to call a callback
X times.
// call a callback `length` times
Array.from({length}, () => callback())
// or generate a random emoji Array
Array.from(
{length: 7},
(v, i) => String.fromCodePoint(
129300 + Math.floor(Math.random() * 20)
)
);
// [ '๐คก', '๐ค', '๐คฅ', '๐ค', '๐คค', '๐คฆ', '๐ค' ]
You can read more about Array
on MDN.
Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 8 days ago.
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 8 days ago.