You can create a new array with default values in JavaScript in one line by using the Array.from()
method and providing a default value. The following example creates an array with 5 elements, each with the default value of 0:
const array = Array.from({length: 5}, () => 0);
console.log(array); // Output: [0, 0, 0, 0, 0]
You can replace 0
with any value that you want to use as the default for each element in the array.
Alternatively, you can also use the Array.fill()
method to achieve the same result:
const array = Array(5).fill(0);
console.log(array); // Output: [0, 0, 0, 0, 0]
+ There are no comments
Add yours