DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Stefan Judis
Stefan Judis

Posted on • Originally published at stefanjudis.com on

TIL: Array.from has a second argument

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.from 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]
Enter fullscreen mode Exit fullscreen mode

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)
  )
);

// [ '🀑', 'πŸ€—', 'πŸ€₯', 'πŸ€›', '🀀', '🀦', 'πŸ€”' ]
Enter fullscreen mode Exit fullscreen mode

You can read more about Array.from on MDN.

Top comments (1)

Collapse
 
kioviensis profile image
Max Tarsis

wow, thx for the tip :)

19 Valuable Github Repositories for Beginners

19 Valuable GitHub Repositories for beginner devs looking to take the first step into the web development career.