Why 'for...of' doesn't work?

Tell us what’s happening:

Hi everyone!

I would appreciate it if you could kindly explain to me what I do wrong that ‘for…of’ statement doesn’t work here:

Your code so far


// Setup
var contacts = [
{
    "firstName": "Akira",
    "lastName": "Laine",
    "number": "0543236543",
    "likes": ["Pizza", "Coding", "Brownie Points"]
},
{
    "firstName": "Harry",
    "lastName": "Potter",
    "number": "0994372684",
    "likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
    "firstName": "Sherlock",
    "lastName": "Holmes",
    "number": "0487345643",
    "likes": ["Intriguing Cases", "Violin"]
},
{
    "firstName": "Kristian",
    "lastName": "Vos",
    "number": "unknown",
    "likes": ["JavaScript", "Gaming", "Foxes"]
}
];


function lookUpProfile(name, prop){
// Only change code below this line
for (let n of contacts) {
if (contacts[n].firstName === name){
    if (contacts[n].hasOwnProperty(prop)) {
        return contacts[n][prop]
    }
    else {
        return "No such property"
    }
}
}
return "No such contact"
// Only change code above this line
}

lookUpProfile("Akira", "likes");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15.

Challenge: Profile Lookup

Link to the challenge:

Hello there,

You appear to be using a for...of loop the way a for...in loop is used.

I recommend you add some console.logs in your code to see what is happening. To help you debug.

Hope this helps

1 Like

Well, for…of loop works in a way that when you use it to loop over an array using the iterator, the iterator is one individual object. In this case, once you loop it with for (let n of contacts) { the iterator n is one single object so inside of it, you should refer it with n and not contacts[n]. Now log the values and you will solve the problem easily.

1 Like

It works with a for..in now, thanks! However, I still don’t understand why do I have to use for..in rather than for...of. The way I think:

  1. We have an array contacts.
  2. The only way to iterate over an array is for...of statement, isn’t it?
  3. While I understand that in order to iterate over properties of an object we should use for in I can’t understand how on Earth this statement iterates over an array :flushed:

I will continue figuring things out anyway but I’d be grateful if you could explain where I made a mistake in my thinking process. Thank you!

and look at that link you posted, look at the examples

you can use a for…of loop, but then you can’t use contacts[n]

1 Like