Initializing an Array with a Single Value in JavaScript | Example code

How to initialize all members of an array to the same value in JS?

There are several ways to create an array in JavaScript to Initializing an Array with a Single Value. Like Array Constructor, map, Array.from(), etc.

Let’s See HTML examples for some of methods

Array Constructor

Use Array Constructor to create an array of specific lengths and then use the fill() method to assign values into each element in an array to a specific value.

Output:

Initializing an Array with a Single Value in JavaScript

Array.prototype.map()

Initialize the array by calling the map() method on the array literal.

Output: Array(5) [ 0, 0, 0, 0, 0 ]

Array.from()

The Array.from() method creates a new Array instance from the specified array. Initialize it with the specified value, map each element to a new value.

Output: Array(5) [ “A”, “A”, “A”, “A”, “A” ]

You can also use Underscore Library.

Q: How to initialize an array with all zeros?

Answer: ES6 introduces Array.prototype.fill. It can be used like this: it’s short and self-describing.

Output:

How to initialize an array with all zeros JavaScript

Do comment if you have any doubts and suggestion on this topic.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.