What is preventing me from being able to return an arrow function?

Presented here is a slightly more advanced function.

The following code functions as intended:

var square = (a) => a * a;

var callAndLog = (func) => {
  return function () {
    var res = func.apply(undefined, arguments);
    console.log("Result is: " + res);
    return res;
  }
};

var squareAndLog = callAndLog(square);

squareAndLog(5);  // Result is 25

However, substituting the arrow function does not produce the desired outcome:

var square = (a) => a * a;
var callAndLog = (func) => {
  return (() => {
    var res = func.apply(undefined, arguments);
    console.log("Result is: " + res);
    return res;
  })
};
var squareAndLog = callAndLog(square);
squareAndLog(5); // Result is NaN

The use of arrow functions can be tricky due to their loose nature. I've attempted to resolve this by using parentheses in various ways without success.

Answer №1

Quoting from the MDN:

An arrow function expression is more concise than a regular function expression and does not have its own bindings for this, arguments, super, or new.target.

Unlike traditional functions, arrow functions do not have an arguments object within their body. If your function relies on arguments, it cannot be converted to an arrow function.

Instead of using arguments, you can use ...args as shown in the example below:

var square = (a) => a * a;
var callAndLog = (func) => {
  return (...args) => {
    var res = func.apply(undefined, args);
    console.log("Result is: " + res);
    return res;
  };
};
var squareAndLog = callAndLog(square);
squareAndLog(5); 

I understand that arrow functions are flexible, which is why I attempted to wrap it in parentheses ().

Wrapping an arrow function in parentheses does not change its behavior. There are very few (if any?) scenarios where this would make a difference.

Answer №2

Arrow functions do not possess the arguments object, but you can utilize the rest parameter syntax (...) like so:

const cube = (num) => num * num * num;
const executeAndLog = (func) => {
  return ((...args) => {
    let result = func.apply(undefined, args);
    console.log("The outcome is: " + result);
    return result;
  })
};
const cubeAndLog = executeAndLog(cube);
cubeAndLog(5);

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

Is the choice of ' and " marks significant?

Similar Question: When to Use Double or Single Quotes in JavaScript Are single quotes valid in HTML/XHTML? When coding in XHTML, HTML, Javascript etc., is there a preference between using single quote (') or double quote (")? Does it make a d ...

HTMX allows for multiple events to be triggered on a single element, each event initiating a unique request

Looking to attach both a click and double click event to the same element in HTMX, with each event triggering a different request (or view). I'm new to using HTMX with Django and I have this list: <li class="list-group-item" hx-get=& ...

How to update specific subelements in MongoDB using targeted queries

Here is an example of my database structure: { "_id" : ObjectId("51e66873f6a6600436000001") ,"email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcbdafb89cbdafb8f2b8b9">[email protected]</a>", ,"attri ...

What could be the reason behind the index not getting properly set for the array that was cloned afterward?

I need assistance with a code snippet that clones an array, resets the index (0, 1, 2 ...), and stores it in a variable named buildingsPayload: console.log('1:', this.buildings) const buildingsPayload = this.buildings.map((building, index) => ...

Utilizing React across various sections of a traditional website

I have transitioned from using Angular 1.x to React in my server-rendered ASP.NET website built on Umbraco CMS. While I am familiar with creating single-page applications (SPAs) using create-react-app, I now need to incorporate React components in various ...

Object transitioning in and out from a different frameset

Looking to create a link that when clicked triggers a JavaScript function to fade in and out two objects from another frameset. Here is an attempt at the code, sourced from various places online. Any help would be greatly appreciated. FRAMESET A: <scr ...

Is it possible to integrate ng-repeat with ng-model in Angular?

Is it possible to link the ng-model of a button with the ng-repeat loop? <a ng-repeat="x in [1,2,3,4]" ng-model="myButton[x]">{{myButton[x]}}</a> In the Controller: var id = 4; $scope.myButton[id] = ' :( '; I am interested in crea ...

Transmit data from Raspberry Pi to Apache Server with strong security measures

Utilizing a Raspberry Pi to collect temperature data and store it in a file Running on a virtual machine, the server uses Apache to host a website (comprised of HTML, PHP, and JavaScript) displaying a graph based on this data I am seeking a secure method ...

What could be the reason my script fails to execute during an AJAX refresh?

As I was working on my project's avatar uploader, everything seemed to be going smoothly until this morning when chaos ensued. It was a moment of pure sadness. Initially, selecting a file would prompt the crop tool to appear immediately, and it worke ...

What is the best way to give stacked bar charts a rounded top and bottom edge?

Looking for recommendations on integrating c3.js chart library into an Angular 6 project. Any advice or suggestions would be greatly appreciated! https://i.sstatic.net/iiT9e.png ...

Retrieving JSON information from a PHP script with AJAX

I am currently experiencing an issue with my PHP script, 'getNews.php'. Despite working correctly in the terminal and returning the expected data, I am encountering difficulties when trying to retrieve this information through JavaScript. <?p ...

A guide to effectively displaying JavaScript variables within a jQuery function

Initially, I believed this was a problem specific to WordPress, but after spending hours attempting to resolve it, I suspect that it may actually be a broader JavaScript issue. I've been grappling with this challenge for a few hours now and I'm ...

Default value of custom Component v-model should be set for v-text-field

Help! I need to set a default value for a v-text-field in a custom component, but all my attempts to override the editedItem.color v-model have failed. I work with Laravel PHP and could really use some assistance from my fellow developers here. I'm n ...

TinyMCE version 5.x - Stand out with a specific selection in a personalized drop-down navigation bar

In my customized TinyMCE 5.x dropdown menu, there are 3 options that adjust the width of the editor. I am looking for a way to indicate the currently selected option, but I am unable to interact with the menu items once they are initialized. It seems like ...

Calculating the Mean of Numbers in JavaScript/AngularJS

Could you help me calculate the average throughput_kbps for TCP protocol in each result array from a JSON response? I am using JavaScript/AngularJS. You can refer to this JSON for more information. Thank you in advance! ...

Using Jquery to dynamically add a textbox with a display:none property set to its value

In this scenario, I have added dynamic rows to a table with textboxes and span tags. Now, I am performing some calculations. In the demo, you will see a textbox for a multiplier factor. Upon change, the last column in my table (Calculated area provided) i ...

Rotate the image as you swipe left or right with Angular's ng-swipe-left and ng-swipe-right features

I am currently utilizing angular's ng-swipe-left and ng-swipe-right to detect swipe events on touch devices. My goal is to rotate an image based on the speed and direction of the swipe while it is still in progress. However, I am facing a challenge as ...

Is the CSS Transition Solely Active for the Introductory Animation?

I'm currently looking to enhance the smoothness of div expansion and contraction on hover using CSS transitions. However, I have noticed that the Transition property only seems to affect the entry animation (i.e., when the mouse hovers and the div exp ...

Updating textures in Three.js

Is there a way to access and modify the data in an exported JSON file using JavaScript? For instance, if I have a material with specific properties like mapDiffuse value that I want to change, how can I achieve this through a JavaScript function? "materia ...

How to Conceal the Search Bar in jQuery DataTables

I am having trouble hiding the default search bar in DataTables. Despite trying solutions from this thread, using bFilter:false completely disables filtering, rendering my search boxes in the footer non-functional. I have created a jsfiddle demonstration. ...