Create an Array with N elements, same Value in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Create an Array with N elements, same Value #

To create an array with N elements containing the same value:

  1. Use the Array() constructor to create an array of N elements.
  2. Use the fill() method to fill the array with a specific value.
  3. The fill method changes all elements in the array to the supplied value.
index.js
const arr = Array(3).fill('a'); console.log(arr); // 👉️ ['a', 'a', 'a']
We used the Array() constructor, to create an array containing 3 empty elements.

We used the Array.fill method to fill the array with a specific value.

The method takes a value and uses it to replace all array elements.

Alternatively, you can use the Array.from method instead of the Array() constructor.

index.js
const arr = Array.from({length: 3}).fill('a'); console.log(arr); // 👉️ ['a', 'a', 'a']

We passed the desired array length as an argument to the Array.from method.

Using the Array.from method is a little more explicit and easier to read than instantiating the Array constructor.

Alternatively, you can use a for loop.

To create an array of N elements containing the same value:

  1. Declare a variable that stores an empty array.
  2. Use a for loop to iterate N times.
  3. On each iteration push the value into the array.
index.js
const arr = []; const total = 3; for (let i = 0; i < total; i++) { arr.push('a'); } console.log(arr); // 👉️ ['a', 'a', 'a']

Using a for loop is a bit more verbose, but many developers are familiar with how loops work.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.