So I am trying to solve the “Basic Algorithm Scripting: Falsy Bouncer” challenge where I most remove falsy values from an array, but my code isn’t working!
can you please take a look and tell me what is going wrong here?
I also put a console.log statement inside the if statement but it’s not being called at all.
function bouncer(arr) {
// Don't show a false ID to this bouncer.
for (let i = 0; i < arr.lenrth; i++){
if (!arr[i]) {
arr.splice(i, 1);
}
}
return arr;
}
bouncer([7, "ate", "", false, 9]);
Then you are changing the array while looping over it. If you add console.log(i, arr[i]) before the if statement you will see it doesn’t follow the sequence of the items in the array as it should - to solve this you should find a different way (not using splice), or looping on the array in a different way
Thanks a lot everyone, now I know that I should not change an array’s length (sorry about the typo earlier) while iterating through it, so I made a new array and pushed only the truthy values to it.
Now my code look like this:
Spoiler:
function bouncer(arr) {
// Don't show a false ID to this bouncer.
let targetArr = [];
for (let i = 0; i < arr.length; i++){
if (arr[i]) {
targetArr.push(arr[i]);
}
}
return targetArr;
}
bouncer([7, "ate", "", false, 9]);
I was actually just having a discussion in a thread about this same problem. While not something you would notice an issue with from the example input array, you should modify your if condition for best practices since while 0 and “” will automatically undergo type coercion and equate to false, NaN, null, and undefined will not. So you would want to do something like if (Boolean(arr[i]))
Ah right, since there is no automatic type coercion for those values for example:
NaN == true returns false
but also
NaN == false returns false
so the condition still accomplishes it’s goal in this case. Definitely an important behavior thing to notice though, I didn’t until you pointed it out to me in my thread.