7/8 Why am I getting a different response for friends[key] and friends.key?


#1

Aren't the response supposed to be the same?

In search function:
When I use console.log(friends.key); It prints undefined.
When I use console.log(friends[key]); It works fine and prints the key

Why is it so?

My code:
var friends={};
friends.bill={
firstName:"bill",
lastName:"gates",
number:"2974299857",
address:["234","dfs"]
};
friends.steve={
firstName:"steve",
lastName:"jobs",
number:"2239749387",
address:["243","fss"]
};
var list= function(friends)
{
for(var key in friends)
{
console.log(key);
}
};
var search=function(name)
{
for(var key in friends)
{
if(friends[key].firstName===name)
{
console.log(friends.key);
return friends[key];
}
}
};
list(friends);
search("steve");


#2

When I use console.log(friends.key); It prints undefined.

That is because friends.key is not defined. key is a dynamic variable, not a static property name. When using a dynamic variable, we must use subscript notation to access the property it refers to.