Consider the following JavaScript code (in a node REPL):
> let a = new Array(10)
undefined
> a
[ <10 empty items> ]
> a.map(e => 1)
[ <10 empty items> ]
> let b = new Array(10).fill(undefined)
undefined
> b
[ undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined ]
> b.map(e => 1)
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
>
When I create an empty array, I'll get 'empty items' which seem to behave differently from undefined
. Can someone explain what is the difference?
When I create an empty array, I'll get 'empty items' which seem to behave differently from undefined. Can someone explain what is the difference?
That's because Array(10)
doesn't populate the array. But it just set the length property to 10
.So, the array created using Array
constructor is simply an object with a length property, but with no items populated.