Kaushani Roy Chowdhury
Kaushani Roy Chowdhury

Reputation: 109

error in a search function in javascript

I am trying to return contact info for "steve", but codecademy is telling me that it is not returning correctly.

It looks like your search function doesn't return contact information for Steve.

I am not able to find any error in this code. Can you help me with finding any syntax or logical errors in the search function that you can see?

var friends = {
    bill: {
        firstName: "bill",
        lastName: "gates",
        number :21415,
        address: ["mcklsn", "wcnskln"]
    },
    Steve: {
        firstName: "bill",
        lastName: "gates",
        number: 21415,
        address: ["mcklsn", "wcnskln"]
    }
};

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

    for (steve in friends)
        console.log(steve);
};

var search = function(name)
{
    for (var i in friends)
    {
        if (friends[i].firstName === name)
        {
            console.log(friends[i]);
            return friends[i];
        }
        else
            console.log("contact doesn't exist!");
    } 
};

Upvotes: 0

Views: 49

Answers (2)

Idos
Idos

Reputation: 15310

You should really pay attention to what you are writing, don't Ctrl-C Ctrl-V everything blindly. You are not calling your friends in the correct names and I would be offended if someone did that to me. Heck, Steve Jobs would be furious if you called him Bill!

This should work:

var friends = {
    Bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: 21415,
        address: ["mcklsn", "wcnskln"]
    },
    Steve: {
        firstName: "Steve",
        lastName: "Jobs",
        number: 21416,
        address: ["mcklsnn", "wcnsklnn"]
    }
};

search("Bill");
search("Steve");

Upvotes: 1

Jimbo Jonny
Jimbo Jonny

Reputation: 3579

Yah, because your Steve property object's firstName is set to "bill".

So that code, searching for a match to 'steve' on the firstName property will not find one...because there isn't one. Both of those object's have 'bill' as their firstName property.

Upvotes: 0

Related Questions