Help! Can somebody tell me what's happening here? =/


#1


Hi, I'm working on the Contact List exercise, 7th step.

https://www.codecademy.com/en/courses/javascript-beginner-en-3bmfN/0/7?curriculum_id=506324b3a7dffd00020bf661


At first, I had this error: "It looks like your search function doesn't return contact information for Steve."
That's why I console logged the key on the else statement, and it only printed 'bill'.

This is my code:


var friends =  new Object();

friends.bill = new Object();
friends.steve = new Object();
friends.monik = new Object();

friends.bill.firstName = 'Bill';
friends.bill.lastName = 'Billy';
friends.bill.number = 111222333;
friends.bill.address = ['1st','Street'];

friends.steve.firstName = 'Steve';
friends.steve.lastName = 'Steven';
friends.steve.number = 444555666;
friends.steve.address = ['2nd','Street'];

friends.monik.firstName = 'Monik';
friends.monik.lastName = 'Carvajal';
friends.monik.number = 777888999;
friends.monik.address = ['CCS','VZLA'];

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

function search(name) {
    for (var key in friends) {
        if (name.toLowerCase() === key) {
            console.log('>> Information for ' + friends[key].firstName + ':');
            console.log(friends[key]);
            console.log('\n');
            return friends[key];
        } else {
            console.log(key); //To check the key
            console.log("Sorry, we couldn't find it\n");
        }
    }
}

But then it just kind of "worked" (or at least the page says I passed the exercise), but the output is just wrong, it prints both the if and else statements the first two times it iterates over friends. As you can see in the output below, the key is "bill" all the time but it prints the correct object.


bill
Sorry, we couldn't find it

>> Information for Steve:
{ firstName: 'Steve',
  lastName: 'Steven',
  number: 444555666,
  address: [ '2nd', 'Street' ] }


bill
Sorry, we couldn't find it

>> Information for Steve:
{ firstName: 'Steve',
  lastName: 'Steven',
  number: 444555666,
  address: [ '2nd', 'Street' ] }


>> Information for Bill:
{ firstName: 'Bill',
  lastName: 'Billy',
  number: 111222333,
  address: [ '1st', 'Street' ] }

If anyone can tell me why is this happening I'll appreciate it.
Thanks.

P.D.: Sorry for my English xD.


#2

If you are going to insist on using code that was not asked for in the instructions...

The else statement is not asked for. The place to have that announcement is after the loop. If nothing is matched, then print the 'Not found" message, outside of the loop.

Do not go it alone, and stay within the instructions as close as possible. Use the information given in the instructions for best results.


#3

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