I hate solving algorithms using code I don’t fully understand. I only resorted to it after being stuck for days upon days. I had a lot of trouble with NaN, and without spoiling too much I just wanted to ask if anybody can explain to me what this portion of code actually means and how it allows me to set NaN as a filter parameter?
i!Number.isNaN
I only took this piece of code as a solution as I was stuck for DAYS on trying to solve it. I had everything else put in place, all my other falsy values were being tested correctly it was just this mindscrew NaN value that I couldn’t quite come to terms with in writing the correct syntax and the only thing stopping me from completing the challenge.
Edit: Opps, my answer isn’t right. Read lionel-rowe below for a more accurate explanation.
I’m not sure about the text as you have it (maybe a type).
Normally* Number.isNaN()* takes an argument and returns true if it’s not number and false if it isn’t. Putting the “!” in front inverts the logic so the whole expression would return true if it is a number. (Not sure why your example has an “i” in front of it and no parameters.)
isNaN(val) returns whether that value is not a number (so would return true for 'apple'), but Number.isNaN(val) returns whether that value is of the type “Number” and is not a number. Confusingly, the type of NaN is “Number”.
Incidentally, you don’t need to be messing around with any specific falsy values to solve this challenge. Bear in mind that filter filters values in the array based on whether the function returns true or false, but it also works with any other truthy or falsy values.
My solution:
function bouncer(arr) {
return arr.filter(function(val) {
return val;
});
}
It’s not hard. I used filter and Boolean object to remove any falsy value like this:
arr.filter(Boolean);
It’s the shortest while still maintainable code I can ever think of.