Array.length
is read and writable. Setting the internal length reference doesn't automatically create empty values. By instaniating an array Array(5)
you're setting the internal length, but creating a blank array. If you were to push a value in its index would be 6 but the array would still only contain one item.
Run these too examples in a console. They're equivalent.
let a = Array(5)
a.push('foo') // length 6
a.push('bar') // length 7
a // [empty × 5, "foo", "bar"]
let b = []
b.length = 5
b.push('foo') // length 6
b.push('bar') // length 7
b // [empty × 5, "foo", "bar"]
a.forEach(i => console.log(i))
// foo
// bar
Using Array.call(null, 5)
produces the same result as above. Its essentially calling Array(5)
with a context of null
; Array.call(null, Array(3))
is creating a nested array, with the first value being an array set to length 3.
There is a shortish hand way described in this answer Create a JavaScript array containing 1...N
var N = 10;
Array.apply(null, {length: N}).map(Number.call, Number)