Why is my code accepted? It returns a reference error


#1


I'm stuck at Searching for a friend.
Well, stuck is not exactly right, the code is accepted and I can proceed to the next exercise. But an error message (see below) is returned instead of the search result that I expected. What is wrong with my code and/or the codecademy website?


ReferenceError: number is not defined


var friends = {
    bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: "(206) 555-5555",
        address: ['One Microsoft Way', 'Redmond', 'Washington']
    },
    steve: {
        firstname: "Steve",
        lastName: "Jobs",
        number: "(508) 5555-55",
        address: ['1 Infinity Loop', 'Mountain View', 'California']
    },
    thomas: {
        firstname: "Thomas",
        lastName: 'Wiesmüller',
        number: "(0711) 2231212",
        address: ['Hofmauerstrasse 49', 'Merklingen', 'Deutschland']
    }
}; 

var list = function(friends) {
   for (var firstName in friends) {
        console.log(firstName);
    }
};
list();

var search = function(name) {
     for (var firstName in friends)
     if (friends[firstName].firstName === name) {
          return friends[firstName, number];
     }
};
search("Bill");


#2

corner cases might sometimes slip through the cracks, the problem is here:

return friends[firstName, number];

you should return:

return friends[firstName];

this will return object bill.

if you want to log something to console, use console.log() on the function call:

console.log(search("Bill"));

what you do here:

for (var firstName in friends)

i find confusing. firstName will hold the friends (bill, steve, thomas), so firstName is not a very logic name for the variable, use friend instead:

for (var friend in friends)

#3

Don't use the same name for the property and the iterative variable, this does not look right:

friends[firstName].firstName

Problem is here:

return friends[firstName, number];

If you want to return values of two properties you have to separately retrieve them and concatenate them:

var search = function(name) {
    for (var friend in friends) {
        if (friends[friend].firstName === name) {
            return friends[friend].firstName + " -> " + friends[friend].number;
        }
    }
};

#4

Thanks guys, that was very helpful!

This way the code is accepted and I get the proper search result:

var search = function(name) {
     for (var searchterm in friends)
     if (friends[searchterm].firstName === name) {
          return friends[searchterm].firstName + " -> " + friends[searchterm].number;
     }
};
search("Bill");

:slight_smile:


#5

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