Javascript ! ! : Explain please

Continuing the discussion from freeCodeCamp Algorithm Challenge Guide: Falsy Bouncer:

    function bouncer(arr) {
// Don't show a false ID to this bouncer.
    return arr.filter(function(val) {
        return !!val ;
});
}

Can you explain the part with ! !val;
How does it work?
(This is catbegemot’s solution).

!! transitions value to boolean. If value was “falsy” (0, null, undefined, NaN etc) it’s gonna be false, otherwise it’s gonna be true.

3 Likes

Technically though, he didn’t need to use !! at all. Simply returning the value is going to evaluate to true or false regardless. That could could be written:

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  return arr.filter(function(val) { return val; }) ;
}
4 Likes