Skip to content
Advertisement

JavaScript property access: dot notation vs. brackets?

Other than the obvious fact that the first form could use a variable and not just a string literal, is there any reason to use one over the other, and if so under which cases?

In code:

JavaScript

Context: I’ve written a code generator which produces these expressions and I’m wondering which is preferable.

Advertisement

Answer

(Sourced from here.)

Square bracket notation allows the use of characters that can’t be used with dot notation:

JavaScript

including non-ASCII (UTF-8) characters, as in myForm["ダ"] (more examples).

Secondly, square bracket notation is useful when dealing with property names which vary in a predictable way:

JavaScript

Roundup:

  • Dot notation is faster to write and clearer to read.
  • Square bracket notation allows access to properties containing special characters and selection of properties using variables

Another example of characters that can’t be used with dot notation is property names that themselves contain a dot.

For example a json response could contain a property called bar.Baz.

JavaScript
Advertisement