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 ?

0

4 Answers 4

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];
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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';

Comments

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');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.