Create an Array with N elements, same Value in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 09 20212 min read

banner

Photo by Jean Gerber

Create an Array with N elements, same Value #

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

  1. Call the Array() constructor, passing it the number of empty elements to be created in the array.
  2. Call the fill() method on the array, passing it the value, that should be repeated for all array elements.
  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 call the Array constructor, to create an array containing 3 empty elements.

To fill the array with values we use the Array.fill method, passing it value, which will replace all the array elements.

A very similar approach is to use the Array.from method to get an array containing N undefined values.

index.js
const arr = Array.from({length: 3}).fill('a'); console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'a', 'a']

We pass the desired array length as a parameter to the Array.from method.

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

The Array.fill and Array.from methods are not supported in Internet Explorer. If you have to support the browser, use the next approach covered in this article.

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

  1. Create an empty array, which will store the values.
  2. Use a for loop to iterate N times. On each iteration push the value into the array.
index.js
// Supported in IE 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 it gets the job done if you have to support Internet Explorer.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee