OberstK
OberstK

Reputation: 150

JavaScript Dot Notation with Objects in Objects

I am playing around with JS at the moment, coming from Java. I did some Tutorials and need some help with the dot and bracket notation in JS.

I made something, I consider an "Object" in JS. Its called "friends". Within this object, there is another object "bill".

var friends = {};
 friends.bill = {
  firstName: "Bill",
  lastName: "Gates",
  number: "(206) 555-5555",
  address: ['One Microsoft Way','Redmond','WA','98052']
 };

 var search = function(name) {
 for(var prop in friends) {
  if(friends[prop].firstName === name) {
   return friends[prop];
  }
 }
};
search("Bill");

This is clearly working as intended. I used bracket notation in the search-function. BUT it isnt clear to me why this version wouldnt work the same way:

 var search = function(name) {
 for(var prop in friends) {
  if(friends.prop.firstName === name) {
   return friends.prop;
  }
 }

In my understanding, bracket and dot notation are used for the same things. I did a search on stackoverflow and I think this question goes the same way, but I think I do not fully understand whats the problem with all the quotation marks.

Upvotes: 1

Views: 881

Answers (4)

Mohamed Ali JAMAOUI
Mohamed Ali JAMAOUI

Reputation: 14689

You can't use a variable with dot notation. The variable won't be evaluated. JavaScript will try to access the property prop from your object which doesn't exist therefore the second solution is not working.

Upvotes: 2

Ketola
Ketola

Reputation: 2767

As mentioned friends.prop.firstName doesn't evaluate the prop as variable, but as property of the friends object.

You could evaluate the string into an object, if you, for some reason, would like to use this type of a notation.

var search = function(name) {
  for(var prop in friends) {
    if(eval("friends."+prop+".firstName) === name) {
     return eval("friends."+prop);
    }
  }
};

Upvotes: 0

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

When you use the bracket notation, you put the name of the property you want to access between the brackets, the name is a string.

When you use the dot notation, you type the property name and not the string containing the property name after the dot.

Your line:

friends.prop

Is interpreted like this by JavaScript:

Look for a property named prop on the object friends, and there is no such property so you get problems.

Upvotes: 2

Pierre Arlaud
Pierre Arlaud

Reputation: 4133

friends.firstName is equivalent to friends['firstName']

Upvotes: 0

Related Questions