Skip to content

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

  • by

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 the 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.

<!DOCTYPE html>
<html> 
<body>

    <script type="text/javascript">
        var n = 5;
        var val = 1;

        var arr = Array(n).fill(val);
        console.log(arr);
    </script>

</body>
</html>

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.

<script type="text/javascript">
        var n = 5;
        var val = 0;
        
        var arr = [...Array(n)].map(x => val);            
        console.log(arr);
    </script>

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.

<!DOCTYPE html>
<html> 
<body>

    <script type="text/javascript">
     var n = 5;
     var val = "A";
     
     var arr = Array.from({length: n}, x => val);
     console.log(arr);
 </script>

</body>
</html>

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.

<!DOCTYPE html>
<html> 
<body>

    <script type="text/javascript">
        var n = 5;
        var val = 0;
        
        var arr = Array(n).fill(val);
        console.log(arr);
    </script>

</body>
</html>

Output:

How to initialize an array with all zeros JavaScript

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

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading