Array.from() mystery

Viewed 118

Someone can explain this?

Array.from(undefined);
// Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

Array.from(null);
// Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))

Array.from('Break this up');
// ["B", "r", "e", "a", "k", " ", "t", "h", "i", "s", " ", "u", "p"]

Array.from(123);
// []

How come the last example returns an empty array? 123 isn't an iterable.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

Array.from(arrayLike [, mapFn [, thisArg]])

arrayLike An array-like or iterable object to convert to an array.

1 Answers

That's because how it's defined in the spec:

  1. Array.from is defined at https://tc39.es/ecma262/#sec-array.from, see step 7 Let arrayLike be ! ToObject(items).
  2. ToObject is defined at https://tc39.es/ecma262/#sec-toobject. See it throws for undefined and null, but does not throw for numbers.
  3. Then return back to Array.from and see that steps 8-13 create and fill an array. But ToObject from number is an empty (it does not have len property and indexed values) object, hence an empty array is returned.
Related