The else in my if/else messing up my function?


#1


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

Hi, my name is Nathan. I'm new here, so I apologize in advance if this question doesn't make sense or if im posting in the wrong area or something.

I finally figured out how to get my search function to work after reading an extremely eloquent and helpful explanation by leonhard.wettengmx.n here, so thanks for that Mr. leonhard.
BUT.....
i dont understand why this code passes:

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

search("Steve");

but this code fails:

var search = function(name){
    for(var i in friends){
        if(friends[i].firstName === name){
            console.log(friends[i]);
            return friends[i];
        } else {
            return "no result";
        };
    };
};

search("Steve");

can anyone explain why the else segment effects the search function in this way?
thanks alot!


#2

Which way though?

If you mean that it prematurely decides that there are no results, then you would need to re-consider when it makes that decision

If you just mean that it doesn't pass then you would need to consider what it does differently by testing it. I just told you what that difference is, but how could you make that observation yourself?


#3

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