Home Ask Login Register

Developers Planet

Your answer is one click away!

Haithomy February 2016

dot-notation vs. bracket notation

I have this JavaScript function:

function test() {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState==4 && xhr.status==200) {
      var obj = JSON.parse(xhr.responseText);
      document.title = obj.page_title;
  xhr.open("GET", "title.php", true); xhr.send();

My question is what the difference between: obj.page_title and obj["page_title"] they all work fine to me and return the same value.


KWeiss February 2016

The two are the same:

The brackets option is useful if you want to use a variable:

var key = 'page_title';

or if your attribute names have unusual characters like spaces in them:

var obj = {
    'title of page': 'title'

obj.'title of page' // wrong
obj['title of page'] // right

Dustin Poissant February 2016

The only difference is if you are using a key with a space in it, or the key is stored in a variable.

This will not work

obj.i have a space = "foobar";

But this will

obg['i have a space'] = "foobar";

If your key is stored in a variable this bracket notation is better than the dot notation.

var o = {
  foo: bar,
  hello: world

for(var key in o){

Post Status

Asked in February 2016
Viewed 3,078 times
Voted 4
Answered 2 times


Leave an answer

Quote of the day: live life