Why aren't these two functions equivalent?


#1



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


The first definition of the search function below follows that of the model solution in the hint and thus is accepted as a correct answer. The second definition of the function is the solution i initially came up with. If brackets and . are both valid methods of accessing object attributes then why aren't these two definitions equivalent (why was my answer not correct)?

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

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


#2

due to the for loop f is now a string, you can see this:

for(var f in friends){
  console.log(typeof(f))
}

not sure typeof is covered, it returns the data type. the dot notation you use, only works if you use the object name, not a string. So you need to use the associative array notation (square brackets), because of f being a string (objects are associative arrays in js, superweird)


#3

I changed my implementation again and used

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

which also works. If what you're saying is true then why does f being a String not cause the above answer to fail?


#4

because f contains a string with the name of the object (steve, bill) but the steve and bill are still inside the friends object, so you need friends[f].firstName.

You first need to access the outer object before you can access the inner object


#5

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