7. Search for a friend, passed but output looks weird?


#1

Hi guys,

I've been cracking my head trying to figure this out. I hope someone here can help. Here's my code. It seems to work but the output definitely doesn't look right. What am I doing wrong?

var friends = {
        bill: {
            firstName: "Bill",
            lastName: "Gates",
            number: "555-1234",
            address: ['One Microsoft Way','Redmond','WA','98052']
        },
        steve: {
            firstName: "Steve",
            lastName: "Jobs",
            number: "555-4321",
            address: ['Two Apple Way','Redmond','WA','98052']
        }
};


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

var search = function(name) {
    for (var key in friends) {
        if (name === friends[key].firstName) {
            console.log(friends[key]);
            return friends[key];
        } 
        else { 
            console.log("We could not find your friend."); 
        }
    }
};

list(friends);
search("Steve");

Here is my output:

And here's what my output looks like: 

bill
steve
We could not find your friend.
{ firstName: 'Steve',
  lastName: 'Jobs',
  number: '555-4321',
  address: [ 'Two Apple Way', 'Redmond', 'WA', '98052' ] }
We could not find your friend.
{ firstName: 'Steve',
  lastName: 'Jobs',
  number: '555-4321',
  address: [ 'Two Apple Way', 'Redmond', 'WA', '98052' ] }
We could not find your friend.
{ firstName: 'Steve',
  lastName: 'Jobs',
  number: '555-4321',
  address: [ 'Two Apple Way', 'Redmond', 'WA', '98052' ] }
{ firstName: 'Bill',
  lastName: 'Gates',
  number: '555-1234',
  address: [ 'One Microsoft Way', 'Redmond', 'WA', '98052' ] }
{"firstName":"Steve","lastName":"Jobs","number":"555-4321","address":["Two Apple Way","Redmond","WA","98052"]}

#2

The search lesson asks us to remove the call to the list() function. Remove that and only the output of search() will be logged.

The thing to note is that we call the function, which logs output for "Steve". The lesson checker runs the code twice, searching for both "Steve" and "Bill". Since the function does the logging, we see the output for those calls.

This statement is not asked for, and it is positioned in the wrong part of the code. If one is set on having that line, then it should follow rather than be inside the loop.


#3

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