Given Array.from
takes an iterable or array-like object as it’s first argument, why does it not throw an error when passed an empty object, like this:
let emptyObject = Array.from( {} )
At iterable is defined as an object that implements the iterable protocol or the iterator protocol. An empty object seemingly does neither:
let emptyObject = {}
console.log(emptyObject[Symbol.iterator])
console.log(emptyObject['next'])
console.log(Array.from(emptyObject))
An Array-like object has a length
property and can be indexed (ref). An empty object does not have a length
property.
let emptyObject = {}
console.log(emptyObject['length'])
console.log(Array.from(emptyObject))
How does an empty object qualify?
3
Answers
Seems it create just an empty array for values not qualified as iterable or array like except
null
andundefined
since no iterator can be read from them (you can read an iterator from non-nullish values, it just will beundefined
). So with no iterator fetched just an empty array is created.When passing a non-empty argument, it seems it checks
[Symbol.iterator]
first, if it doesn’t exist, it then checkslength
property. If neither of them exist, fallback to an empty array.Array.from()
works with array-like objects. More specifically it only really needs thelength
property:This is defined in starting at step 7. of the Array.from algorithm
The LengthOfArrayLike itself defers to ToLength which is defined as the following:
A missing
length
meansargument
isundefined
which at step 1. would be converted to zero.