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?
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.
filter(Boolean)` just removes values from a list which are "falsey", like empty strings or null.
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.
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.
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]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With