Difference to loop


#1

Could someone please explain why we don't use loop but key in friends (for (var i=0; iAlso, I don't really understand what the key is for (I know 'key' could be any word but I don't understand the purpose of that placeholder).
Why could it not just be
for (var firstName in friends) {
if (friends.firstName ===name) {
console.log(friends);
return friends;
}

Thank you!


#2

maybe this example can help you understand how and why we use it like this ...

Example :
var obj = {a:1, b:2, c:3};

for (var prop in obj) {
console.log("obj." + prop + " = " + obj[prop]);
}

// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

Also you say you for (var firstName in friends) because firstName in already a parameter and in this condition you are creating a new variable.


#3

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

It's a little easier to see above that key is a dynamic variable that takes on several values in the loop. Because it is not a static property that exists in the object, we cannot use dot notation.