Member-only story
JavaScript — How to create and fill an empty array with a given size?
Nov 17, 2022
Solution
const arr = Array(5).fill("");
console.log(arr); //prints out ["","","","",""]
console.log(arr[0]); //prints out ""
1) To create new array which, you cannot iterate over, you can use array constructor:
Array(100)
or new Array(100)
2) You can create new array, which can be iterated over like below:
a) All JavaScript versions
- Array.apply:
Array.apply(null, Array(100))
b) From ES6 JavaScript version
- Destructuring operator:
[...Array(100)]
- Array.prototype.fill
Array(100).fill(undefined)
- Array.from
Array.from({ length: 100 })
You can map over these arrays like below.
Array(4).fill(null).map((u, i) => i)
[0, 1, 2, 3][...Array(4)].map((u, i) => i)
[0, 1, 2, 3]Array.apply(null, Array(4)).map((u, i) => i)
[0, 1, 2, 3]Array.from({ length: 4 }).map((u, i) => i)
[0, 1, 2, 3]