Q7 "Search for a Friend"


#1


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

"bill
steve

ReferenceError: firstName is not defined

congratulations, You've finished this course"


Replace this line with your code. 
var friends = new Object(); {

friends.bill = new Object();
friends.bill.firstName = "Bill";
friends.bill.lastName = "Gates";
friends.bill.number = "131166";
friends.bill.address= ['321 Fake Street', 'NSW', 'Australia', '2000'];

friends.steve = new Object(); 
friends.steve.firstName = "Steve";
friends.steve.lastName = "Jobs";
friends.steve.number = "000";
friends.steve.address= ['123 Fake Street', 'NSW', 'Australia', '2000'];
}


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

var search = function(name) {
    for (var name in friends) {
        if(friends.name.firstName === name) {
            console.log(friends.name);
            return(friends.name);
    
     
        }
    }

};
search(firstName);


#2

var search = function(name) {
    for (var name in friends) {
        if(friends.name.firstName === name) {
            console.log(friends.name);
            return(friends.name);

The variable name in the for loop is wiping the variable in the parameter. Give it a different name, such as friend.

for (var friend in friends) {

}

When accessing an object property with a loop, the key/property name is assigned to the iterator variable. Since that variable is not a property of the object, it must be accessed using subscript notation.

if (friends[friend].firstName === name) {

}

#3

bill
steve
undefined
undefined
undefined
ReferenceError: firstName is not defined

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

list(friends);

var search = function(name) {
for (var friend in friends) {
if (friends[friend].firstName === name) {
console.log(friends.name);
return(friends.name);

    }
}

};
search(firstName);


#4

As mentioned earlier, friends[friend]

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

#5

Hi mtf. This fact about using subscript notation is crucial, but I cannot recall where, when and how it was taught me. Are square brackets meant by subscript notation?


#6

Yes. They indicate an index in an array, and a key in an object.

array[index]   => index is an integer

object[key]    => key is a string

Not sure where it is discussed, but it must come up early in the track in one form or another.

"bracket notation" is the term used, if I recall. 'subscript notation' is my term. I probably didn't pick it up here, but elsewhere in my reading over the years. Same meaning.


#7

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