This post will discuss how to initialize an array with a single value in JavaScript.

There are several ways to create an array in JavaScript with all its elements initialized with a specific value:

1. Using Array Constructor

The idea is to use Array Constructor to create an array of specific length and then use the fill() method to assign each element in an array to a specific value.

Download  Run Code

2. Using Array.prototype.map() function

Alternatively, you can initialize the array by calling the map() method on the array literal. The following code example shows how to implement this:

Download  Run Code

3. Using Array.from() function

The Array.from() method creates a new array instance from the specified array and optionally map each array element to a new value.

To create an array, the idea is to pass an empty object to the Array.from() method with length property defined. To initialize it with the specified value, map each element to a new value.

Download  Run Code

4. Using Underscore Library

The Underscore library _.range method can generate a sequence of values in JavaScript. You can call the fill() method to fill the generated values with the given value.

Download Code

That’s all about initializing an array with a single value in JavaScript.