7. Search for a friend explanation?


#1


So, I solved the question with the hint given to me but I pretty much copy/pasted the whole thing and I'd love a deeper explanation of what I just wrote. I kind of get it but could one of you guys explain what the hell I wrote?

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


#2

I assume your code includes an object of friend objects.

Your loop starts by initializing a variable to sort through the properties of your friends object. This object will have all of the properties that you wrote into it, I assume labelled with names of your friends.

Your loop then checks each of these properties for a 'firstName' property of their own. If they have the property AND the value it holds is equal to the name provided to your search function it will log the entire friend property to the console and return it to wherever called the function.

The return value is only for the context that called the function, if you don't explicitly return a value a function will return 'undefined', a falsy value. Sometimes a function returns a value to use it, others just returning a value is treated as 'true' or proof that the operation succeeded.


#3

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