What is the main difference between object.name and object["name"] in javascript. Which one is better?
4 Answers
.name
has to use a valid identifier.
[]
can use any string, including one in a variable.
Creating a string is marginally less efficient than using an identifier.

- 914,110
- 126
- 1,211
- 1,335
Using indexer notation allows you to specify the property name as an arbitrary expression (such as a variable), whereas dot notation requires a valid identifier in source.
You should use dot notation wherever you can.
You should only use indexer notation if you need to specify a runtime expression or an invalid identifier.

- 868,454
- 176
- 1,908
- 1,964
-
1With emphasis on *need* to. 99.9% of the times you can choose your own names and then you should just not choose an invalid identifier name. – Ingo Bürk Sep 24 '13 at 14:49
main difference between object.name and object["name"] in javascript
There is no difference. They reference exactly the same element in a JS object.
Which one is better?
The first one object.name
is better if you know the name of the element you're referencing, because it's cleaner and easier to read. It's also slightly more efficient, but not so much that it makes a significant difference.
If you want a dynamic name (eg a key from a loop, or a name built up from concatenated strings) then you have to use the second syntax object["name"]
.

- 166,037
- 39
- 233
- 307
Using bracket notation instead of dot notation is useful for the following scenarios:
- When you need to iterate over an array of strings like fields=["name","address",...] as
data[fields[i]]
- When you will be compiling your code with the closure compiler (dot notations get renamed and break)
- If you want to differentiate types of variables by using one type a dot and others as bracket
- When the user/client side will be selecting what data field to use.
alert(data[arguments[1]])

- 7,676
- 1
- 30
- 52