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!
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With