I always assumed Array.from
behaves the same as Array.map
for array. But it seems that for array with no initial values, they are totally different.
arr = new Array(5);
range = Array.from(arr, (v,idx) => idx); // [0,1,2,3,4]
new_arr = arr.map((v, idx) => {return idx;}); // [undefined, undefined,undefined, undefined,undefined]
So Array.from
was still able to get the indices, while arr.map
here just skips through all the values, actually it never calls the callback function.
How does JavaScript handles an array with no initial values?
new Array(5)
creates a sparse array, that is an array with a length
of 5
but actually no entries - the elements 0-4 are not just undefined
, they actually don't exist. (0 in arr === false
)
You are writing above that the result of map
is [undefined, undefined, ...]
but actually it is another sparse array with no elements. In Chrome Devtools, you'd see this as [empty × 5]
instead.
Array.from
specifically has the purpose to create a regular array out of array-like things. It basically checks for a length
property and creates a new array out of whatever is returned from [0]
, [1]
, ..., [length - 1]
. Therefore, it turns the sparse array into a dense array with 5x undefined
in it, and your callback is called for elements 0-4.
Array.prototype.map
however just iterates over the (existing!) elements in the array and returns a new array with the mapped values. Note that the sparse array has no elements, hence your callback is never called, and the returned array looks the same as before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With