0

What is the main difference between object.name and object["name"] in javascript. Which one is better?

Rajesh Dhiman
  • 1,888
  • 1
  • 17
  • 30

4 Answers4

2

.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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    With 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
0

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"].

Spudley
  • 166,037
  • 39
  • 233
  • 307
0

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]])
technosaurus
  • 7,676
  • 1
  • 30
  • 52