-3

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.

Haithomy
  • 73
  • 2
  • 8
  • They simply different notations that do the same thing. – jcubic Feb 08 '16 at 14:02
  • `obj.page_title` is identical to `obj["page_title"]`. The latter is useful when the property name is in a variable or not a valid identifier. – John Dvorak Feb 08 '16 at 14:02
  • Just a friendly tip: This question has nothing to do with JSON.parse, even if that is how you create your object. I would consider changing the title. If you change your title though, you will find that this question has been asked a lot of times here before. You will most likely get a lot of downvotest because of this. It is nothing personal, there is just not anything to benefit the community as a whole in this post, so you should probably delete the question, and be happy that you've got a good answer out of it anyway :) – jumps4fun Feb 08 '16 at 14:06

2 Answers2

1

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
KWeiss
  • 2,954
  • 3
  • 21
  • 37
-1

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]);  
}
Dustin Poissant
  • 3,201
  • 1
  • 20
  • 32
  • 1
    That's not the _only_ difference. The other answer shows another use case. – John Dvorak Feb 08 '16 at 14:03
  • There are many more characters than just the space that are invalid in JavaScript identifiers, and thus can't be used with dot notation. – Oka Feb 08 '16 at 14:04