Andrey Bienkowski
Andrey Bienkowski

Reputation: 1715

Why do I get TypeError: 0 is not a function when passing Array.from as a callback to Array.flatMap?

Passing Array.from as a callback to Array.flatMap causes an error: "TypeError: 0 is not a function"

const x = ["12"].flatMap(Array.from)
console.log(x)

Despite this Array.from is usable as a function normally:

const f = Array.from
console.log(f("12"))

I have found a way around this:

const x = ["12"].flatMap(e => Array.from(e))
console.log(x)

I would like someone to tell me:

  1. Why do I get an error?
  2. Why do I get such an astonishingly unhelpful error message?

Upvotes: 1

Views: 751

Answers (2)

Igor Bykov
Igor Bykov

Reputation: 2822

Array.from accepts up to 3 parameters, the second one being map function while .flatMap will pass to it iteration index as the second parameter.

So, on the first iteration, Array.from will recieve 0 as a second parameter, which, indeed, is not a function that Array.from expects.

To demonstrate it more clearly, here is a snippet. This line:

["12"].flatMap(Array.from);

is functionally equivalent to:

Array.from("12", 0, ["12"]);

which is an incorrect signature for Array.from.

Upvotes: 3

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6769

It happends because the flatMap passes more than 1 argument to the callback. The second argument is the index of the element. Array.from function expects a replacer function in the second argument. So this shortened version passed an index in place of a function.

What you're doing is equivalent to calling:

Array.from("12", 0)

Instead of a proper replacer like:

console.log(Array.from("12", x => x + x));

Upvotes: 3

Related Questions