Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of (x => x) in JavaScript arrow function using array.every() method

looking for an explanation on this line of code. I understand arrow functions to a degree. The purpose of this code snippet/challenge is; "Given any number of parameters, return true if none of the arguments are falsy." I've seen the solution like this:

const nothingIsNothing = (...args) => args.every(x => x)

Examples of arguments and the expected results are:

nothingIsNothing(0, false, undefined, null) ➞ false

nothingIsNothing(33, "Hello",  true,  []) ➞ true

nothingIsNothing(true, false) ➞ false

I just don't understand how the section (x => x) evaluates to either truthy or falsy. Can someone explain how this works? I hope this makes sense lol. Thanks!

like image 381
Kurt Willrich Avatar asked Mar 01 '23 22:03

Kurt Willrich


1 Answers

With .every, if any of the return values from the callback are falsey, the .every evaluates to false, otherwise it evaluates to true. So x => x as a callback means: take every value in the array and return it immediately. If all are truthy, the whole .every evaluates to true, else false.

It's doing the same logic as this:

const nothingIsNothing = (...args) => {
  for (const arg of args) {
    if (!arg) return false;
  }
  return true;
};

Or, implementing something similar to .every yourself:

// don't do this in real code, this is just an example

Array.prototype.myEvery = function(callback) {
  for (const item of this) {
    if (!callback(item)) return false;
  }
  return true;
};

console.log([1, 2, 3].myEvery(x => x));
console.log([1, 2, 3, 0].myEvery(x => x));
like image 101
CertainPerformance Avatar answered Apr 28 '23 20:04

CertainPerformance