1

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.

1
  • 1
    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 abject which doesn't exist therefore the second solution is not working Commented Nov 25, 2013 at 11:16

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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

Comments

0

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);
    }
  }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.