0

There's one aspect of the new Array.from method that I'm not understanding. I'm reading the through the Description section on MDN, and came across the following:

Array.from() has an optional parameter mapFn, which allows you to execute a map function on each element of the array (or subclass object) that is being created. More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array. This is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type.

I'm not understanding:

...the intermediate array would necessarily have values truncated to fit into the appropriate type

I'm not sure what this is saying, since we're going from a typed array to a normal Array (using Array.from). It's not like any incorrect types will be in the typed array. Also, the resulting Array from Array.from() will of course accept any type like normal JS arrays do.

Could anyone give insight into what this is trying to say or what I'm missing?

1 Answer 1

4

The array subclasses inherit the from method from Array, so you can e.g. call

const iter = (function*() { for (var i=0; i<512; i++) yield i }());
const arr = Uint8Array.from(iter);
console.log(arr); // Uint8Array(512) […, 250, 251, 252, 253, 254, 255, 0, 1, 2, 3, …]

The resulting array is an Uint8Array and has the values truncated respectively. If you provided a mapping function, it would have made a difference whether you used Uint8Array.from(iter, fn) or Uint8Array.from(iter).map(fn).

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @Bergi, that makes much more sense now. So Uint8Array.from(... returns an instance of Uint8Array because from() was called on the Uint8Array subclass, even though I believe the from() method is defined at the top level built-in Array class correct?
@qarthandso Yes, exactly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.