Why the for-in loop prints numbers in the console

why the for-in loop prints numbers in the console not the object itself


function whatIsInAName(collection, source) {
const arr = [];
// Only change code below this line

for(let obj in collection){
console.log(obj)
}
// Only change code above this line
return arr;
}

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

Challenge: Wherefore art thou

Link to the challenge:

When in doubt, google it. MDN is a great resource for JS. If I google “mdn for in”, I get taken here. There, I read:

The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by), including inherited enumerable properties.

So, it goes over an object and iterates the properties/keys. You’ve given it an array. That’s OK, in JS, arrays are a type of object. What are the keys in an array? The indices of the array. That is why it is logging the indices. If you want, you can use those indices to access the various elements. You might also consider looking into for...of or an array prototype method.

2 Likes