At the time of writing MDN's description of the Array.from function states:
Array.from()has an optional parameter mapFn, which allows you to execute a map() function on each element of the array being created.More clearly,
Array.from(obj, mapFn, thisArg)
has the same result asArray.from(obj).map(mapFn, thisArg),
except that it does not create an intermediate array.
However, it does not have exactly the same behaviour, as demonstrated here:
function mapFn(...args) {
console.log(...args);
}
let obj = { 0: "value", length: 1 };
let thisArg = { };
Array.from(obj, mapFn, thisArg);
Array.from(obj).map(mapFn, thisArg);
Array.from does not pass on a third argument to the callback.
This is in line with the ECMAScript 2020 specification on Array.from:
Call(mapfn, thisArg, « nextValue, k »).
While for Array.prototype.map the specification has:
Call(callbackfn, thisArg, « kValue, k, O »).
Evidently, the above quote from MDN is not entirely correct.*
Question
Why this difference? Would it not have made more sense to actually have Array.from work like a map() function as stated in the above quote from MDN?
* Some time after posting this question, Mozilla Contributors added a clause to the paragraph quoted above:
..., and
mapFnonly receives two arguments (element,index) without the whole array, because the array is still under construction.
But this "because" seems to mix up the original data with the result of the mapping. The array that is being constructed, is the result array, while the third argument that the Array#map callback takes is the source object. Also there a result array is still under construction... That is a red herring in my opinion. It would well be possible to pass as third argument the source object that had been passed as first argument to Array.from.
thisArgis supposed to be literally thethisvalue passed to the callback. Not the third parameter of themapfunction. These are two different things.Array.fromdoes not invokemapas MDN confusingly states, it ismap.