For...of vs. for...in

Tell us what’s happening:

Hi!

Would anyone be able to explain why for…of doesn’t work with the array here. Through, for…in works well. Through my research, for…in is usually used for objects and properties while for… of works with arrays/strings. Please help! Thank you!

Your code so far


function bouncer(arr) {
// Don't show a false ID to this bouncer.
let trueArr = [];
for(let i of arr) {
if (arr[i]) {
  trueArr.push(arr[i])
  }
}
return trueArr;
}

console.log(bouncer([7, "ate", "", false, 9]));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36.

Challenge: Falsy Bouncer

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer

i isn’t an index. It is the value itself. So your if is trying to check if(arr[7]), if(arr['ate']), etc.

1 Like