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?