Laser
Laser

Reputation: 5439

What's the difference between syntax obj.obj.key and obj[obj].key for accessing values?

It seems that in the context of a for loop the syntax regarding objects changes.

Why shouldn't the console.log()'s run the same thing? The first runs as expected, the second renders an error 'steve is not defined':

var friends = {
    steve: {firstName: "Steve",                    lastName: "Jobs", 
            number: "none"
            }
};

friends.bill = {
    firstName: "Bill", 
    lastName: "Gates", 
    number: "Hidden"
};

console.log(friends.steve.firstName)
console.log(friends[steve].firstName)

Normally, I wouldn't expect the format obj[obj].key to be used, but it appears that in the following example with a for loop, the syntax obj.obj.key does not work, but conversely obj[obj].key does:

var friends = {
};

friends.steve = {
    firstName: "Steve",
    lastName: "Jobs",
    number: "none",
};

friends.bill = {
    firstName: "Bill",
    lastName: "Gates",
    number: 'Hidden',
};

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

search("Steve")

What is happening that is causing these two syntaxes to behave differently in these contexts?

Thanks!

Upvotes: 2

Views: 303

Answers (1)

Paul Draper
Paul Draper

Reputation: 83235

friends.steve

is another way of writing friends['steve']

which is different than

friends[steve]

The first is the string 'steve', the second is the variable steve, which could be 'bob', 'steve', 1, or anything else.


Example:

var obj = {steve:1, bob:2};
var steve = 'bob';

console.log(obj.steve);    // 1
console.log(obj['steve']); // also 1
console.log(obj[steve]);   // 2

or equivalently,

var obj = {steve:1, bob:2};

console.log(obj.steve);    // 1
console.log(obj['steve']); // also 1
console.log(obj['bob']);   // 2

Upvotes: 3

Related Questions