Why code is giving error?

Tell us what’s happening:
Describe your issue in detail here.
if I check with if (arr[i]===true) it gives wrong result,
if I do like this if(arr[i]) it gives correct results, why it is so?

   **Your code so far**

function bouncer(arr) {
 let newArr=[];
 for (let i=0; i<arr.length; i++){
 if (arr[i]===true){
   newArr.push(arr[i]);
   
 }
 }
return newArr;

}

console.log(bouncer([7, "ate", "", false, 9]));
   **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36

Challenge: Falsy Bouncer

Link to the challenge:

1 Like

if (arr[i] === true) checks that the value at arr[i] is true

if (arr[i]) checks that the value at arr[i] is truthy

You need to transform the value you want to check into a boolean first with “!!” before you can compare it to “true”, like so:

if (!!arr[i]===true)

(pssst, if (!!arr[i] === true) is exactly the same as if (arr[i]) because the if statement coerces to boolean for you)

1 Like

Thank you, cleared my doubt.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.