Search for a friend


There is not a problem with the code but I'm hoping someone can explain something for me. In the search function there is a for/in loop used and I understand the general use of it and it's function but one thing I can never wrap my head around is the use of the variable or the purpose it serves, in this case called "prop". For instance, in the if statement that follows it matches "friends[prop].firstName === name". I get that it is comparing the friends.firstName to the parameter entered for the search function but there is no property or key between friends object and the firstName property/key so why is the [prop] variable there? In my mind it seems it should be just "if (friends.firstName === name)" instead but it doesn't work without the [prop] being tucked in the middle. Can someone explain this? I tried to test this by running the same search function using a regular for loop but there seems to be some background code at work preventing this from displaying.

var friends = {};
friends.bill = {
  firstName: "Bill",
  lastName: "Gates",
  number: "(206) 555-5555",
  address: ['One Microsoft Way','Redmond','WA','98052']
friends.steve = {
  firstName: "Steve",
  lastName: "Jobs",
  number: "(408) 555-5555",
  address: ['1 Infinite Loop','Cupertino','CA','95014']

var list = function(obj) {
  for(var prop in obj) {

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



prop is each key in the object as the object loops through its keys. To access a particular keys values you need to do an associative lookup on the object using the key.

Hence, the reason you need


So, for example, if you have an object

fruits = {
  'banana': { count: 2 },
  'apple': { count: 3 }

And you want to get the keys of each property in the object, then you could do:

for(var fruit in fruits) {
// banana
// apple

Now, if you wanted to get the count of apples in the fruits object you would need to look it up in the object like so

// 2

If you wanted to get the count of every fruit in the fruits object you could do:

for(var fruit in fruits) {
// 2
// 3

Hope that helps :slight_smile:


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