Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript .filter() true booleans

function bouncer(arr) {   // Don't show a false ID to this bouncer.     function a(b) {       if(b !== false) {         return b;       }     }      arr = arr.filter(a);     return arr; }  bouncer([7, 'ate', '', false, 9]); 

I have to return true boolean statements only, and when I run this code, it works. However, I am quite confused because my "if statement" will work whether it's b !== true or b !== false. Could someone please explain the reason why this works both ways?

like image 382
jyoon006 Avatar asked May 03 '15 17:05

jyoon006


People also ask

What does filter Boolean do in JS?

filter(Boolean) is really helpful for removing null and undefined values, but it's important to bear in mind that there are quite a few confusing cases above... this trick will remove items with a value of 0 from your array! That can be a significant difference for interfaces where displaying a 0 is perfectly fine.

What does filter Boolean mean?

filter(Boolean)` just removes values from a list which are "falsey", like empty strings or null.

What is filter Boolean I typescript?

filter(Boolean as any as ExcludesFalse); This works because you are asserting that Boolean is a type guard, and because Array. filter() is overloaded to return a narrowed array if the callback is a type guard.


2 Answers

Apparently .filter() was introduced in ES5.

This definitely helped me wrap my mind around what's going on here. Hope it helps!

Essentially, writing:

arr.filter(Boolean) 

is the same as writing:

arr.filter( function(x) { return Boolean(x); });  

since Boolean() is also a function that returns truthy when true and falsy when false!

Example:

var a = [1, 2, "b", 0, {}, "", NaN, 3, undefined, null, 5];  var b = a.filter(Boolean);  // [1, 2, "b", {}, 3, 5];  

Source: here.

like image 127
leonelaguzman Avatar answered Sep 23 '22 08:09

leonelaguzman


I was solving a similar problem and came up with this:

function bouncer(arr) {   return arr.filter(Boolean); } console.log(bouncer([7, 'ate', '', false, 9]));
like image 43
hello world Avatar answered Sep 20 '22 08:09

hello world