tags:

views:

89

answers:

3

If I do this,

var element = {};
alert(element);
element[name] = "stephen";
alert(element.name);

Why doesn't element.name work?

+17  A: 

When using bracket notation, (unless it's a variable) it needs to be in qoutes, like this:

var element = {}; 
alert(element); 
element["name"] = "stephen"; 
alert(element.name);

You cant test it out here. To explain what I mean by "unless it's a variable", this would also work:

var myVariable = "name";
element[myVariable] = "stephen";
Nick Craver
+8  A: 

Because name should be in quotes. This works:

var element = {};
alert(element);
element['name'] = "stephen";
alert(element.name);

Try it.

Adam
A: 

this is the reason why you may want to get an object's property dynamicly. For example:

you have a variable but you can't be sure its value. Server send you the variable value so you should write like this.

obj[name].age // here the name is a variable and it can be change in every page refresh for example

but if you want to set obj['name'] = 'Lorenzo' you have to use quotes.

Think like that obj[name] is used for set, obj['name'] is used for get.

Lorenzo

Lorenzo