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.

Answers


KWeiss February 2016

The two are the same:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

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

var key = 'page_title';
obj[key];

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){
  console.log(o[key]);  
}

Post Status

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

Search




Leave an answer