1

I tried my best to think of a name of this question, I'll change it if I can get some terminology to help

Best way I can describe it is this

obj1 = {
    "a":{"var":1},
    "b":{"var":2},
    "c":{"var":3}
}

// What's the difference between
resulta = obj1['a']['var']

// and...
resultb = obj1.a.var

So, what's the difference between using [''] and . ?

I realize you can only use . to run functions, but is that the only difference?

Is one method faster than the other? (even a little?)

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
iNk
  • 83
  • 11
  • 1
    You can call functions using array accessors: `var obj = {someFunc: function() { console.log('hi'); }};` - `obj['someFunc']();` works just fine. – dontGoPlastic May 14 '12 at 22:17

3 Answers3

1

The first method with square brackets is handy if you're dynamically building your object's property keys:

var myDynamicKey = "a";
var result = obj[myDynamicKey]["var"];
var result = obj["someOtherKey_" + myDynamicKey]["var"];

The second one is definitely preferred if you know what the properties are in advance.

Note you can mix and match them:

var result = obj[myDynamicKey].var;

I'd be willing to bet that accessing properties using dot notation is faster, but I have no actual data to support that.

dontGoPlastic
  • 1,772
  • 14
  • 22
1

If you use the [''] then you can pass the name of the key in as a dynamic variable... which can change at run time. If you use the .key.key method, then you have to know at build time what the keys are.

Example:

var keys = ['name','phone','email'];
var object = {"name": ,"phone": , "email"};
function updateKeys(name,phone,email){
    for(var i = 0; i < keys; i++){
        object[keys[i]] = arguments[i]
    }
}

vs

function updateKeys(name, phone, email){
    object.name = name; 
    object.phone = phone;
    object.email = email
}

The [''] way is much more flexible and allows for more code resuse. Most libraries will use this, or some homegrown replacement of the [''] way of doing things.

frosty
  • 21,036
  • 7
  • 52
  • 74
0

There are various websites with information about this.

http://www.quirksmode.org/js/associative.html
or
http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_)
or
http://www.mongodb.org/display/DOCS/Dot+Notation+(Reaching+into+Objects)

The first I would call dot notation which can be used to access Methods and Properties of an object, and the 2nd is Associative Array.

Tim B James
  • 20,084
  • 4
  • 73
  • 103