JavaScript property access: dot notation vs. brackets?

(Sourced from here.)

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

var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax

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:

for (var i = 0; i < 10; i++) {
  someFunction(myForm["myControlNumber" + i]);
}

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.

var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax

Leave a Comment