Falsy Bouncer Problem :
Remove all falsy values from an array.
Falsy values in JavaScript are false, null, 0, “”, undefined, and NaN.
This was my original solution that works:
function bouncer(arr) {
//Don’t show a false ID to this bouncer.
var emptyVar = [];
for(var i=0; i < arr.length; i++) {
if(arr[i]) {
emptyVar.push(arr[i]);
}
}
return emptyVar;
}
bouncer([7, “ate”, “”, false, 9]);
but I know it’s probably not what FCC wanted me to do because of the Filter() and Boolean hints.
I looked online to refractor my code, and I found this simple solution:
function bouncer(arr) {
return arr.filter(Boolean);
}
and it works. I read the MDN and still have trouble understanding how this fully works. MDN said filter() usually has a call back function. I can’t wrap my head around how just inserting Boolean will make it go through and remove all the items in the array that are false. Can someone help please explain?
Boolean is an object wrapper. This gets used behind the scenes in JavaScript all the time. Basically, you pass it a value and it returns true (a boolean primitive) if it’s a truthy value and false if it’s falsey.
I was a bit confused about filter(Boolean) because I assumed it would remove all Booleans so true and false would be removed. But it only removes the false or falsey apparently.
So when I read
I realized this -
DescriptionEDIT
filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.
So I guess as filter goes through the array if something doesn’t come back true the new array created doesn’t include it.