0

I've discovered some very odd behavior from Array.from. It appears that it does not work as a callback function directly when mapped over an array of Array-like objects. I've tested in Chrome.

Here's some test code (ES6):

const fails = () => {
  const x = {
    0: 'help',
    length: 1
  };

  const y = [x].map(Array.from); // will throw an Error
  return y;
};

const works = () => {
  const x = {
    0: 'help',
    length: 1
  };

  const y = [x].map(item => Array.from(item)); // will work
  return y;
};

console.log(works());
console.log(fails());

https://jsfiddle.net/dox6wnya/

This is very peculiar behavior. I'm wondering why this happens.

1 Answer 1

4

.map passes three arguments to its callback (currentValue, index, array), and .from accepts three arguments (arrayLike, mapFn, thisArg). The types of arguments don't match and/or produce unexpected results; in particular "0 is not a function", where 0 is the index argument passed to mapFn. The only real compatible argument is the first one, which is why it's the only one you should pass.

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

3 Comments

Why do I only see 2 args on Array.map?
map takes two args but passes three args to callback.
Ah. That makes sense. Thanks.

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.