2

I used to believe that there is no difference between them but after seeing this piece of code, all my information about objects in Javascript failed.

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

This code works. But

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

this doesn't.

Thanks for explaining.

Barmar
  • 741,623
  • 53
  • 500
  • 612
DifferentPseudonym
  • 1,004
  • 1
  • 12
  • 28
  • 7
    `friends.x` is the same as `friends["x"]`, not `friends[x]`. – Barmar Apr 19 '15 at 10:06
  • possible duplicate of [Accessing Properties in object](http://stackoverflow.com/questions/14086573/accessing-properties-in-object) and [JavaScript property access: dot notation vs. brackets?](http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – Qantas 94 Heavy Apr 19 '15 at 10:36

2 Answers2

7

friends.x is not the same thing as friends[x], it's the same thing as friends['x'].

When you use friends[x] the value x can be a variable (or any expression), but when you use friends.x the x is a literal name, it won't use the variable x.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • But, how can I write it with '.'. Or can't I? – DifferentPseudonym Apr 19 '15 at 10:14
  • 1
    @MindlessRanger: You can only use the `.` notation with a known name. The only way to access properties dynamically using that notation is to create code dynamically, e.g. `eval('friends.' + x)`, but there is no good reason to do it that way. – Guffa Apr 19 '15 at 10:17
  • Thanks, accepting as answer now. – DifferentPseudonym Apr 19 '15 at 10:19
  • 1
    @MindlessRanger: Another significant difference is that when using dot notation and a property name literal (`friends.x`), the property name is limited to the [rules for *IdentifierName*](http://www.ecma-international.org/ecma-262/5.1/#sec-7.6) (a limited set of characters, can't start with a digit, etc.); but when using brackets notation and a string (`friends["x"]`), the property name can be anything (even just a single space, `" "`). – T.J. Crowder Apr 19 '15 at 10:23
0

As @Guffa already explained, friends.x and friends['x'] are the same, the difference in those approaches is that when you use [] this syntax you can use variables, 'property like this', or reserved words, this is good when you do not know exactly the property you will need.

Vitaliy Terziev
  • 6,429
  • 3
  • 17
  • 25
  • Actually, as of ES5, you can already use reserved words with dot notation (you couldn't in ES3 and before, but that was changed in ES5, by changing [§11.2.1](http://ecma-international.org/ecma-262/5.1/#sec-11.2.1) to use *IdentifierName* instead of *Identifier*). – T.J. Crowder Apr 19 '15 at 10:41