You can initialize an Array in JavaScript in a myriad of ways. However sometimes you may need to initiate it in a specific way for a given problem at hand. Here are different methods to initiate an Array that you may find useful for different scenarios
Initiate an empty Array
let arr = Array(); let arr = Array(5)
Initiate an Array of specific length with default values
Array(5).fill(0)
// [ 0, 0, 0, 0, 0 ]
Array.from({length: 5}, () => 0)
// [ 0, 0, 0, 0, 0 ]
// WARNING: SAME EMPTY ARRAY BY REF, mutates all references
Array(5).fill([])
// [ [], [], [], [], [] ]
let ref = Array(5).fill([])
ref[0].push('⚠')
//[ [ '⚠' ], [ '⚠' ], [ '⚠' ], [ '⚠' ], [ '⚠' ] ]
Note there is a difference between initiating an Array with the constructor function and the .from method:
Array(3) // [ <3 empty items> ]
Array(3).fill() // [ undefined, undefined, undefined ]
Array.from({length: 3}) // [ undefined, undefined, undefined ]