2

Possible Duplicate:
JavaScript property access: dot notation vs. brackets?

I am now reading some of open source javascript project codes and i see that sometimes they access object property like person.name but sometimes they access like person['name'].

For me dot notation is so much clear against other. Dot notation is easy to write and read but in source code i see that they are sometimes used dot notation sometimes [] braces notation and i am trying to understand what is the reason of it.

What can be reason of it ?

Community
  • 1
  • 1
Freshblood
  • 6,285
  • 10
  • 59
  • 96

4 Answers4

7

First it can be dynamic with a string:

 var key = 'name';
 person[key];

Second, it also supports other symbols that aren't supported

 var key = 'first-name';
 person[key];
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
6

Here's a use case (having impossible property name)

var obj = {};
> undefined
obj['first name'] = 'Ivan';
> "Ivan"
obj['first name']
> "Ivan"
obj.first\ name
> SyntaxError: Unexpected token ILLEGAL
obj.first name
> SyntaxError: Unexpected identifier
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
2

Here is a very good reason for using the brackets, where we're passing in the property name as a parameter:

function showProperty(propertyName) {
    alert(person[propertyName]);
}

showProperty('name');
showProperty('age');

Here is another good reason, where we can access the 'headers' property of request using dot-notation, but we can not access the 'Content-Type' property of request.headers using dot-notation, because it contains a -.

request.headers['Content-Type'] = 'text/html';
Linus Thiel
  • 38,647
  • 9
  • 109
  • 104
1

It's very usefully to use this notation in methods, where you send your attribute name as parameter for example.

var Obj = function(){
    this.abc = function(){
        alert("abc!!!");
    };
    this.qqq = function(){
        alert("QQQ!!!");
    };
}

var showAlert = function(param){
    var myObj = new Obj();
    myObj[param]();
};

showAlert('abc');
Ph0en1x
  • 9,943
  • 8
  • 48
  • 97