Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.from() mystery

Tags:

javascript

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.

like image 851
kerafyrm kerafyrm Avatar asked Jun 15 '26 18:06

kerafyrm kerafyrm


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.
like image 78
zerkms Avatar answered Jun 17 '26 08:06

zerkms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!