2

If I do this,

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

Why doesn't element.name work?

Peter Mortensen
31.3k22 gold badges110 silver badges134 bronze badges
asked Oct 21, 2010 at 18:19

3 Answers 3

17

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";
answered Oct 21, 2010 at 18:20
Sign up to request clarification or add additional context in comments.

Comments

8

Because name should be in quotes. This works:

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

Try it.

answered Oct 21, 2010 at 18:20

Comments

0

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

You have a variable, but you can't be sure of its value. The 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 changed in every page refresh, for example.

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

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

Peter Mortensen
31.3k22 gold badges110 silver badges134 bronze badges
answered Oct 21, 2010 at 19:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.