The arrow lambda callback function in JavaScript's Array Every method is returning undefined when passing an argument

Utilizing the JavaScript Array Every method for validation, I encountered an issue when passing arguments with a specific condition while using the JavaScript arrow lambda callbackFn.

To illustrate the problem, let's consider a simple example.


The syntax for the Array.prototype.every() function is as follows:

every(callbackFn)
every(callbackFn, thisArg)

In this scenario, I am performing validation on whether all elements in an array are even or odd.

Validation works fine when the array.every() method callbackFn is defined as a regular JavaScript function. Here is an example to demonstrate this:

const checkEven = function (num)  {
   console.log(this.isEven, num);
   return num%2 === (this?.isEven ? 0 : 1);
}

evenArrary = [2, 4, 6, 8];
console.log('All elements are even: ', evenArrary.every(checkEven, {isEven: true}));

oddArray   = [1, 3, 5, 7];
console.log('All elements are odd: ', oddArray.every(checkEven, {isEven: false}));

However, when I switch the callbackFn to a JavaScript arrow lambda function, passing arguments no longer functions correctly.
Here is an example demonstrating this situation:

const checkEven = ((num) => {
   // 'this' is an empty object here & this.isEven = undefined
   console.log(this.isEven, num);
   return num%2 === (this?.isEven ? 0 : 1);
});

evenArrary = [2, 4, 6, 8];
console.log('All elements are even: ', evenArrary.every(checkEven, {isEven: true}));

oddArray   = [1, 3, 5, 7];
console.log('All elements are odd: ', oddArray.every(checkEven, {isEven: false}));

Output: https://i.sstatic.net/xFly9v3i.png

The reason behind why passing arguments doesn't work when using an arrow lambda function for callbackFn remains unclear to me.

Is there a solution to this issue while still utilizing the arrow lambda callback function?

Answer №1

Many have pointed out that arrow functions behave differently in relation to this keyword.

Nevertheless, it is possible to adapt your code to work with arrow functions like so:

const checkEven = thisArg => num => {
 console.log(thisArg.isEven, num);
 return num%2 === (thisArg?.isEven ? 0 : 1);
}

evenArrary = [2, 4, 6, 8];
console.log('All are even: ', evenArrary.every(checkEven({isEven: true})));

oddArray   = [1, 3, 5, 7];
console.log('All are odd: ', oddArray.every(checkEven({isEven: false})));

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

Elements in Motion

Working on a parallax effect, I've managed to assign unique scroll speeds to (almost) every element. Moreover, these elements are programmed not to activate their scroll speed until they enter the viewport. Below is the JavaScript code for trigger co ...

handlebars and expressjs having trouble displaying the data

Hey there! I'm currently working on an application with express.js and handlebars. I've set up a get method to retrieve employee data when the user enters http://localhost:3000/id/2 in their browser. The id should be 2, and it's supposed to ...

Having difficulties initiating the JS server due to insufficient information

After creating a fresh react-native project, I encountered a problem when running the command react-native run-android. The project consistently gets stuck at the message info Starting JS server.... Below is the output of the command: $ react-native run- ...

Use Jquery to smoothly scroll to the top offset of

I've been successfully utilizing jquery ScrollTo from https://github.com/balupton/jquery-scrollto, but I'm interested in incorporating the "offset top" add-on. Has anyone had experience setting this up? I'm not quite sure how to implement it ...

Issues with Markdown text editor code, table, and list functionalities are causing malfunction

Looking for a solution to use markdown editor for writing blog posts? If you're facing issues with code blocks, list items, tables, etc., not working correctly after publishing your markdown-based posts, while other elements like images, links, and bo ...

Ways to receive JavaScript console error messages to aid in debugging your code

Currently, I am developing a Web Application and facing an issue with capturing console errors. Specifically, I need to capture errors related to network connectivity issues, such as when the network is down or slow causing responses from the server to be ...

What is the best way to fill a JavaScript array with only the divs that are currently displaying as block elements?

In my JavaScript code, I am attempting to populate an array using jQuery. Within a <section> element, there are multiple <div> elements, but I only want to add the ones that are visible (with CSS property display: block) to the array. HTML: & ...

Navigating through the endless scroll behavior in Twitter using CasperJS (PhantomJS)

Having trouble with infinite scrolling on Twitter, as the page is not loading new content even when scrolling to the bottom. To test if any content loads at all, I have used the following code snippet: casper.open('https://twitter.com/<account> ...

Can you explain the significance of these vertices in the box geometry in THREE.js?

After creating a box geometry using the code below: const hand1geo = new THREE.BoxGeometry(2, 0.01, 0.2); const material_sidehand = new THREE.MeshBasicMaterial({ color: 0x3cc1b7 }); const sidehand = new THREE.Mesh(hand1geo, material_sidehand); ...

Finding the following index value of an object within a foreach loop

In my code, I have an object called rates.rates: { AUD="1.4553", BGN="1.9558", BRL="3.5256"} And I am using the following $.each loop: $.each( rates.rates, function( index, value ){ console.log(index); }); I have been attempting to also log the n ...

Objects that are included into an array will end up with an undefined value

Currently, I am in the process of coding a command for my Discord bot that involves adding items to an array of objects stored within a JSON file. To achieve this functionality, I have implemented the following code snippet: let rawdata = fs.readFileSync(& ...

implementing jqBarGraph on my webpage

Hey there! I have been trying to add a graph to my HTML page for quite some time now. After doing some research, I discovered that using the jqBarGraph plug-in makes it easier to create the desired graph. Below you will find the code that I have on my webp ...

Transfer dynamically generated table data to the following page

Seeking guidance on a common issue I'm facing. I am creating a table using data from Firebase upon page load, and I want users to click on a row to view specific details of that item. It may sound confusing, but it will make more sense with the code p ...

Retrieve the values from the rows and columns in the array located below the specified

I am working on a task that involves generating multiple lines on a binary image based on specified length and angle parameters. My goal is to retrieve the row/column values along with pixel values under these lines and organize them into a python list. T ...

Make your redux actions cleaner and easier to manage with typescript

In our react/redux application, each time we introduce a new action, we find ourselves duplicating a significant amount of boilerplate code. I am looking for a solution that can streamline this process and help us automate it. While the example provided is ...

Angular - Keeping component data in sync with service updates

Within my Angular application, I have several components utilized in an NgFor loop which all rely on a common service. My goal is to create a system where if one component alters a value within the shared service, that updated value will automatically pro ...

Leveraging express functions in Node.js framework

Currently, I am delving into the world of nodeJS and have stumbled upon a great collection of tutorials. The tutorials are focused on teaching me about a powerful framework known as express. In order to utilize express effectively, one must also grasp the ...

Display a notification for recurring users with the exception of first-time visitors

We have been working on updates for an older website and want to notify returning or repeat visitors of the changes. After making updates, some browsers continue to show a cached version of the site to returning visitors, causing them to see the site as b ...

Transferring characters from one array to another character array

Is there a faster method available to copy an array of Characters to an array of chars? I can create a method that converts each Character in the array to char, but I'm wondering if there is a pre-existing method similar to Arrays.copyOf for arrays of ...

Is there a way to ensure that the bootstrap popover always appears in the center of the screen, similar to a Modal

Hi, I need to implement popovers or tooltips from Bootstrap. I am currently calling the popovers using a classname on many buttons. Is there a way to have all button popovers open in the center of the screen using JavaScript? Thank you. ...