-1

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.

  • 2
    [`filter`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) coerces the return value to a boolean. See the [spec (step 7.c.ii)](//tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.filter). Note that `.filter(Boolean)` is the idiomatic version. – Sebastian Simon Oct 21 '22 at 13:51

1 Answers1

0

JavaScript has the concept of Truthy and Falsy values.

Using Array.filter(Boolean) or Array.filter(ele => ele) is pretty much the same. Boolean will cast your value to a boolean value which can only be true or false. 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:

Array.filter(ele => {
  return ele !=== undefined || ele !== null || ele !== false || ele !== '' || ele !== 0 || ele !== NaN
})
marcobiedermann
  • 4,317
  • 3
  • 24
  • 37