Algorithm Scripting - how did this work? (arr.filter)

Basic Algorithm Scripting : Falsy Bouncer

I was using JavaScript’s .filter() method to solve this problem, when I unexpectedly stumbled upon a solution. Can anybody explain to me why arr.filter(ele => ele) removed all of the falsy values from the array? I was planning on adding some logic to filter further in order to solve the problem but noticed that this simple piece of code worked. Problem and solution below:

Problem:

Remove all falsy values from an array:
bouncer([7, “ate”, “”, false, 9]);

Falsy values in JavaScript are false , null , 0 , "" , undefined , and NaN .

Solution:

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
let newArr = arr.filter(ele => ele);
console.log(newArr);
return newArr;
}

bouncer([7, "ate", "", false, 9]);

A value that is “falsy” is one that is treated as false by logical operators and returns false when cast to a boolean. The filter() method looks at the return value of the callback function and removes all elements that return a falsy value.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.