DEV Community

Greg Fletcher
Greg Fletcher

Posted on

Instant Arrays, Javascript

Here's a cool way to quickly make arrays in Javascript.

let array = Array(10).fill()

This creates an array with ten slots in it. I usually find this useful if I need to quickly iterate over a list in React. For me, this is a nice quick way to check if my styling is working. For example, what if we wanted to know what a component would look like with 10 list items compared to 20.

Example below

const List = () => <div>{Array(10).fill().map((_, i) => <p key={i}>Text</p>)}</div>;

What's great about this is that I just change one number and get an entirely different numbered array. No need to manually type out the array yourself.

Sometimes though it's also useful to have an ordered array. This is also quite easy to achieve.

let array = Array(5).fill().map((_, index) => index +1); // 1,2,3,4,5

Here we're just using the index of the array and returning it after adding 1. This gives us an array with five elements ranging from 1 to 5

If we didn't need an ordered array we could just provide .fill an argument and fill the entire array with that value.

let array = Array(100).fill(2); // [2,2,2,2,2...etc]

So there we have it, I hope that you learned something from this article. I love learning new coding tricks so definitely let me know if you have anything cool to share in the comments!

Top comments (0)