DEV Community

Greg Fletcher
Greg Fletcher

Posted on

5 1

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!

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

nextjs tutorial video

📺 Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay