xs4bcg
Last Updated: June 25, 2019
·
131
· greenroots

JavaScript: Quick way to initialize array with static values

The easiest way I found so far is to use Array.fill() function.

Use-case

Need to create an array in Javascript and fill it with some static value, may be null or any other values.

Tips

Usage 1

Array(5).fill(null); // Create array of 5 elements with null values

This method has additional optional arguments like, arr.fill(value, start, end). This also helps in modifying an existing array to have some static values on the chosen indexes.

Usage 2

var arr = [1, 23, 46, 58];
arr.fill(57, 1, 3);
// output: [1, 57, 57, 58]

Hope it was useful!