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:

// Given: var foo = {'bar': 'baz'};  // Then var x = foo['bar'];  // vs.  var x = foo.bar; 

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

Asked on July 16, 2020 in Java Script.
Add Comment
13 Answer(s)

Dot notation is always preferable. If you are using some “smarter” IDE or text editor, it will show undefined names from that object. Use brackets notation only when you have the name with like dashes or something similar invalid. And also if the name is stored in a variable.

Answered on July 16, 2020.
Add Comment

Let me add some more use case of the square-bracket notation. If you want to access a property say x-proxy in a object, then - will be interpreted wrongly. Their are some other cases too like space, dot, etc., where dot operation will not help you. Also if u have the key in a variable then only way to access the value of the key in a object is by bracket notation. Hope you get some more context.

Add Comment

An example where the dot notation fails

json = {     "value:":4,    'help"':2,    "hello'":32,    "data+":2,    "????":'????',    "a[]":[        2,       2    ] };  // correct console.log(json['value:']); console.log(json['help"']); console.log(json["help\""]); console.log(json['hello\'']); console.log(json["hello'"]); console.log(json["data+"]); console.log(json["????"]); console.log(json["a[]"]);  // wrong console.log(json.value:); console.log(json.help"); console.log(json.hello'); console.log(json.data+); console.log(json.????); console.log(json.a[]);  

The property names shouldn’t interfere with the syntax rules of javascript for you to be able to access them as json.property_name

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.