Possible Duplicate:
JavaScript property access: dot notation vs. brackets?
Let's consider I have an object:
var o = { x:1, y:2 };
What is the difference when I access a property like this:
o.x
Compared to this:
o["x"]
Possible Duplicate:
JavaScript property access: dot notation vs. brackets?
Let's consider I have an object:
var o = { x:1, y:2 };
What is the difference when I access a property like this:
o.x
Compared to this:
o["x"]
Those are called Member Operators, and there is a good bit of information on them in that link.
The only real differences are that the bracket notation allows you to disobey variable naming rules and do things like:
o["3213adascas #@%!"] = 5;
While the following is obviously a syntax error:
o.3213adascas #@%! = 5;
Also since bracket notation takes in a string you can use variables with it:
var o = { x:1, y:2 };
var member = 'y';
console.log(o[member]); // Outputs 2
o.x
is effectively just syntactic sugar for o["x"]
. They do the same thing. However, the square bracket notation allows you for example to use the value of a variable as the property name to access:
var someString = "x";
o[someString];
As well as this, if the property name is not a valid identifier, the square bracket notation must be used:
var myObj = {
"space property": 1
};
myObj["space property"];
There is no difference - exactly the same thing ... but does enable keys with spaces / obscure characters :
o['something here'] = "test";
will work for example, but this wont :
o.something here = "test";
The square bracket notation has an advantage. You can set properties dynamically.
From JavaScript Garden
var foo = {name: 'Kitten'} foo.name; // kitten foo['name']; // kitten var get = 'name'; foo[get]; // kitten foo.1234; // SyntaxError foo['1234']; // works
Both notations are identical in their workings, with the only difference being that the square bracket notation allows for dynamic setting of properties, as well as the use of property names that would otherwise lead to a syntax error.
These two do exactly the same thing. However, bracket notation (o["x"]
) allows you to do two things that you cannot do with dot notation (o.x
):
Access a property with an arbitrary string. For example, o["function"]
and o["432 %^$ ==="]
are valid syntax, but o.function
is not valid because function
is a keyword, and o.432 %^$ ===
is not valid because it constitutes a syntax error.
Set a dynamic property of an object. You can do var str = "prop";
and access o[str]
with bracket notation.