How to Initialize a New Array with Values in JavaScript
Learn how you can initialize a new array with a set of values in JavaScript.
Simple Solution
One simple solution to initialize a new array with a defined size and default value is to use the fill()
method introduced in ES6. Here’s an example:
1 | Array(12).fill(0); |
This code will create a new array with a length of 12, and each element in the array will be initialized with the value 0.
By using the fill()
method, you can easily initialize an array with a specific value for all its elements.
Tags: JavaScript, arrays, initialization, fill method, ES6