TypeError: The function cannot be performed on the value of 0 in the Array.from

I encountered a peculiar error while attempting to utilize Array.from with Array.prototype.map.

let fn = Array.from.bind(Array); // [Function: bound from]

fn('test') // [ 't', 'e', 's', 't' ]

['test'].map(s => fn(s)) // [ [ 't', 'e', 's', 't' ] ]

['test'].map(fn) // TypeError: 0 is not a function

Complete Error Message:

TypeError: 0 is not a function
    at Function.from (native)
    at Array.map (native)
    at repl:1:10
    at REPLServer.defaultEval (repl.js:260:27)
    at bound(domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:429:12)
    at emitOne (events.js:95:20)
    at REPLServer.emit (events.js:182:7)
    at REPLServer.Interface._onLine (readline.js:211:10)

Can someone provide insight on what could be causing this issue?

Answer №1

map executes its callback function with three parameters: The entry, the index, and the object being iterated over. Array.from anticipates that if a second argument is provided to it, it's a mapping function, so it attempts to apply it to every "element" forming the array. However, since the index, 0, on the first call isn't a function, the execution of Array.from fails.

To illustrate this differently,

['test'].map(fn)

is not equivalent to

['test'].map(e => fn(e))

but actually corresponds to

['test'].map((e, i, a) => fn(e, i, a))

...where e represents the entry, i is its index, and a is the "array" undergoing iteration by map. Since i is not a function, Array.from encounters an error.

A similar scenario can also occur with various other array methods like forEach, some, ...


If you encounter this issue frequently, you might find it beneficial to have a utility function to extract only the first parameter:

function passOneArg(f) {
    return function(a) { return f.call(this, a); };
}

which can be used in the following way:

['test'].map(passOneArg(fn))

or potentially even

function limitArgs(f, count) {
    return function() {
        return f.apply(this, Array.prototype.slice.call(arguments, 0, count));
    };
}

then

['test'].map(limitArgs(fn, 1))

Although these may have unimpressive names, they serve the purpose effectively... :-)

Answer №2

Utilize the power of lodash's unary function

import * as _ from 'https://cdn.jsdelivr.net/npm/lodash-es/lodash.min.js'
['ef', 'gh'].map(_.unary(Array.from))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 13.0 version is experiencing issues when trying to run the "ng serve" command

After installing the npm module, I encountered a problem while using node.js version 14.17.6. I am a beginner in Angular and struggling to find a solution due to not using the latest Angular CLI version. Any help would be greatly appreciated. Thank you in ...

Initiate a click action upon receiving a focus event

I can't seem to figure out why this code is not functioning as expected: $('a').focus( function() { $(this).click(); }); Context: I am working on developing a form where navigating through different elements (such as textboxes) will au ...

React - triggering a router link action before the link is assigned a value

In this scenario, the issue arises because the URL changes before the link receives a value. The state is being received directly through the component but by the time it happens, the component has already been clicked. This results in the value being as ...

Is there a way to access comprehensive data pertaining to an ID through Ajax?

I need help with an Ajax call. Below is the code I currently have: $.ajax({ async: true, url: 'test/', type: 'POST', datatype: 'text json', data: { id: id, }, success: function(data) { // Retrieve the da ...

Exploring methods to detect when a PHP page has been printed using the 'ctrl+p' shortcut and then subsequently updating

Hey there! I'm currently managing a php website that functions as an accounting system. Within this system, there are receipts, invoices, and other forms of documentation in use. However, I've encountered a problem with the main table in my myS ...

Obtain the number of elements rendered in a React parent component from a switch or route

I'm currently working on a component that is responsible for rendering wrapper elements around its children. One challenge I'm facing is determining which elements are actually being rendered as children. I've implemented functions to ignore ...

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

Utilize React.js ThemeProvider to dynamically change themes based on routing

Hey everyone, I have a question regarding changing the theme provider based on the route in my code snippet: const rootElement = document.getElementById('root'); ReactDOM.render( <ThemeProvider theme="MyThemes.default& ...

Is it possible to pass a PHP array to JavaScript without using Ajax?

Currently, I have a JavaScript function that utilizes Ajax to fetch an array of data from PHP and dynamically populates a dropdown menu. Everything is functioning as expected. However, I am beginning to feel that using Ajax for this task might be a bit ex ...

Tips for preventing the need to create a function within a loop

Currently, I am in the process of collecting data through REST calls. I have created a function that accesses a "directory" endpoint to retrieve a list of individuals. While I can easily obtain details about their children, I need to make individual AP ...

How I am able to access this.state in React without the need for binding or arrow functions

Understanding the concept of arrow functions inheriting the parent context is crucial in React development. Consider this React component example: import React, { Component } from 'react'; import { View, Text } from 'react-native'; i ...

Can an object serve as a property name for another object?

Can this be achieved using JavaScript? I'm attempting to assign the property name of an object as a "HTMLInputElement": var el = $('#something').get(0), obj = {}; obj[el] = 'some random data'; Unfortunately, it ...

Having difficulties grasping the concept of how to communicate effectively with my MySQL database

Apologies in advance for asking a question that may have been answered elsewhere, but I've been struggling for hours to transfer the information into my own program. Despite my attempts, I always encounter the same obstacles. So, I decided it would be ...

Strip newline characters from information in AngularJS

What is the recommended approach for detecting and formatting the "\n\n" line breaks within text received from the server before displaying it? Check out this Fiddle: http://jsfiddle.net/nicktest2222/2vYBn/ $scope.data = [{ terms: 'You ...

Having trouble getting tailwind dark mode to work on next.js?

I have set up a custom boilerplate using next.js(10.0.5) with preact(10.5.12), typescript(4.1.3), and tailwind(2.0.2). I am attempting to incorporate a dark mode feature from Tailwind. I followed the instructions from next-themes in order to add the dark ...

The AngularJS framework is failing to disable the autocomplete feature for the input field with a password type

I have attempted to disable auto-complete for the password input, but it doesn't seem to be working. Below is a sample of my code: <form name="testfrm" ng-submit="test(testfrm)" autocomplete="off"> <input type="password" id="passwor ...

Whenever I click on a button, I want to modify the background color of my react-modal

Having an array of images with clickable overlays and a modal that changes the background color based on the overlay name when clicked is the goal. However, passing this value as a prop proves challenging since the images are generated through a function a ...

Is the memory usage of node.js proportional to the number of concurrent requests, or is there a potential memory leak?

Running the following node.js code: var http = require('http'); http.createServer(function(req,res){ res.writeHead(200,{'Content-Type': 'text/plain'}); res.write("Hello"); res.end(); }).listen(8888); Upon starting the server ...

The CSS styling for a pie chart does not seem to be functioning properly when using jQuery's

https://i.stack.imgur.com/kEAKC.png https://i.stack.imgur.com/03tHg.png After examining the two images above, it appears that the CSS is not functioning properly when I try to append the same HTML code using JavaScript. Below is the snippet of my HTML co ...

All Event Monitor

Is it possible to use Event Listeners in jQuery to display information when a specific word is clicked? For example, showing a definition when a word is clicked. Thanks, Adam. I need help with creating a feature where clicking on a person's name in a ...