Tell us what’s happening:
How does this code work?
How the filter method knows that the element pass is truthy and not falsy?
function bouncer(arr) {
return arr.filter(Boolean);
}
Your code so far
function bouncer(arr) {
// Don't show a false ID to this bouncer.
//Below is my code
/*
let arr1 = [];
arr.filter(function(x) {
if(!!x === true) {
arr1.push(x);
}
});
return arr1;
*/
}
bouncer([7, "ate", "", false, 9]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer
The function are passing as an argument to your .filter
function(x) {
if(!!x === true) {
arr1.push(x);
}
}
Is only replaced by another native function called Boolean
…
The Boolean
returns true if if the argument you pass to it is truthy.and false otherwise.
PS: You don’t need to manually push into arr1..filter
implicitly returns a copy of filtered array…
function bouncer(arr) {
return arr.filter(function (x) {
return !!x;
});
}
1 Like
Is that true? I would think that was an implementation detail of the engine?
Array.prototype.filter ( callbackfn [ , thisArg ] )
Let selected be ToBoolean(Call(callbackfn, T, «kValue, k, O»)).
SpiderMonkey JS::ToBoolean
No, it’s in the spec, conditionals convert to a Boolean to allow them to evaluate properly, the semantics don’t work otherwise — in a strongly typed language, this wouldn’t be an issue, because putting non-boolean expressions in there is impossible, but JS isn’t strongly typed so it just tries to make sure the program won’t explode via coercion
I think I need more of this to understand filter and boolean.
thanks man
I posted a video on this same topic yesterday… Hope this helps…
1 Like
Thanks for the video adityaparab