How to use the spread syntax with Array.fill() In Javascript
Using the spread syntax `[…Array(size)]`, where size is the desired array length, creates an array of that size. Combining it with `.fill(0)` fills the array with the specified value (`0` in this case), resulting in an array of the desired size filled with the specified value.
Example : Here we are using the spread syntax with Array.fill() to create an array of a given size in JavaScript
let size = 5;
let arr = [...Array(size)].fill(0);
console.log(arr);
Output
[ 0, 0, 0, 0, 0 ]
To more about Arrays in JavaScript please go through Arrays in JavaScript
Create an array of given size in JavaScript
Creating an array of a specific size can be achieved through various methods, each suited to different situations. In this article, we will explore several approaches to creating arrays of a desired size, accompanied by examples for each method.
Below are the following ways:
Table of Content
- Using JavaScript array() constructor
- Using apply() and map() Methods
- Using JavaScript Array.from() Method
- Using for loop
- Using the spread syntax with Array.fill()