How to create an Array with N elements, same Value in JavaScript

Create an Array with N elements, same Value

Create an array with N elements containing the same value using fill() method

To create an array with N elements that all have the same value:

  1. Call the Array() constructor to create Array objects.
  2. Pass N elements as parameter. e.g. Array(arrayLength)
  3. Use the fill() method to populate the array with a specific value. e.g. Array(arrayLength).fill('Hello')
const theArray = Array(2).fill('Hello');

console.log(theArray);
Create an array with N elements containing the same value using fill() method
Create an array with N elements containing the same value using fill() method

Note: Array() constructor can be called with or without new. Both create a new Array instance.

Explanation –

In this example, We used the Array() constructor and pass 2 to create an array containing two empty elements.
Later used the Array.fill method to populate the empty elements with a specific value Hello in the array.

Create an array with N elements containing the same value using Array.from() method.

Array.from() can be used as an alternative to the Array() constructor.

const theArray = Array.from({length: 2}).fill('Hello');

console.log(theArray); 
create an array with N elements containing the same value with Array.from method
Create an array with N elements containing the same value using Array.from().

The code is creating an array with 2 elements, and each element is filled with the letter ‘Hello’.

ℹ️ The Array.from method is more explicit and easier to read than the Array constructor.

Create an array with N elements that all have the same value using a for loop.

You can also use a for loop to create an array of N elements containing the same value.

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

  1. Create a new empty array.
  2. Use a for loop to iterate a set number of times.
  3. On each iteration, push the value into the new empty array.

Example –

const theArray = [];
const elements = 2;

for (let i = 0; i < elements; i++) {
  theArray.push('Hello');
}

console.log(theArray);
Create an array with N elements containing the same value using a for loop.
Create an array with N elements containing the same value using a for loop.

Explanation –

The code above is creating an array called ‘theArray’ and adding two elements to it. The elements are strings that say ‘Hello’.

How to create an Array with N elements, same Value in JavaScript.

Summary

There are three ways to Create an Array with N elements, same Value:

  1. Using Array() constructor.
  2. Using Array.from() static method.
  3. Using for loop.