Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why else block is executed even though if condition is true?

I was practicing some JavaScript on Codeacademy few minutes ago and I found something confusing. Here is the code:

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) {
    console.log(prop);
  }
};

var search = function(name) {
  for(var prop in friends) {
    if(friends[prop].firstName === name) {
      console.log(friends[prop]);
      return friends[prop];
    }
    else {
      return  "contact not found";
    }
  }
};

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

The problem is that when I pass the string "Steve" as an arg in the search function, it returns the condition "Contact not found" while when I pass the string "Bill" as an arg in the same search function, it displays the contact information.

How is that possible? What am I doing wrong?

like image 347
Ahmed Magdy Avatar asked Jan 15 '16 19:01

Ahmed Magdy


2 Answers

In your code, in the first iteration of the loop, the prop value is something else apart from Steve. So, the if condition fails, reaches the else part and returns contact not found immediately.

But, you should return not found message only when none of the objects's firstName matches, like this

function search(name) {
  for (var prop in friends) {
    if (friends[prop].firstName === name) {
      return friends[prop];
    }
  }
  return "contact not found";
};
like image 130
thefourtheye Avatar answered Oct 29 '22 08:10

thefourtheye


else {
  return  "contact not found";
}

You're returning not found as soon as you find a contact that doesn't match.

You shouldn't give up until you run out of items.

like image 40
SLaks Avatar answered Oct 29 '22 08:10

SLaks