Why else is the block satisfied, although if the condition is true?

A few minutes ago I practiced JavaScript on Codeacademy, 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 arg in the search function, it returns the condition "Contact not found", when I pass the string "Bill" as an argument in the same search function, it displays contact information.

How is this possible? What am I doing wrong?

+5
source share
2 answers

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

But you should only return a not found message if none of the firstName objects matches, like this

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

You return not found as soon as you find a contact that does not match.

You must not give up until you have completed the points.

+4
source

Source: https://habr.com/ru/post/1240718/


All Articles