Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript Array Every method passing argument showing undefine for arrow lambda callback function

I’m using JavaScript Array Every method for some validation and when I’m passing arguments with some condition, then it’s not working with JavaScript arrow lambda callbackFn.

Let me describe the issue with simple example.


According to Array.prototype.every() documentation, it’s syntax is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

every(callbackFn)
every(callbackFn, thisArg)

In this example I’m validating, all array elements are even or odd.

When I write array.every() method callbackFn as a normal JavaScript function, then validation is working.
This is example as follows:

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}));

Now, I’m changing that callbackFn as a JavaScript arrow lambda function, then passing argument is not working.
Example as follows:

const checkEven = ((num) => {
   // 'this' is 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:
enter image description here

Now, I don’t understand why passing arguments is not working when write callbackFn as a arrow lambda function.

Why this is happening ?
Is there any way to do this with arrow lambda callback function ?

>Solution :

As others have commented, arrow functions behave differently regarding this.

However, you can make your code work with arrow functions like this:

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})));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading