I just solved this challenge on freecodecamp
Remove all falsy values from an array. Return a new array; do not mutate the original array.
Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.
Hint: Try converting each value to a Boolean.
i solved mine this way:
function bouncer(arr) {
return arr.filter(function(ele){return ele});
}
as opposed to this solved by freecodecamp:
function bouncer(arr) {
var check = arr.filter(function(i) {
return Boolean(i);
});
return check;
}
I can't understand why mine works correctly when called with bouncer([7, "ate", "", false, 9]);, since i'm just returning the variable in the test function without doing the boolean conversion.
JavaScript has the concept of
TruthyandFalsyvalues.Using
Array.filter(Boolean)orArray.filter(ele => ele)is pretty much the same.Booleanwill cast your value to a boolean value which can only betrueorfalse. If you return just the value, it gets evaluated either as truthy or falsy. If you would like to write it in a very explicit way you could do the following: