Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
159
rated 0 times [  161] [ 2]  / answers: 1 / hits: 64865  / 14 Years ago, sun, may 30, 2010, 12:00:00

I'm trying to work out what is considered valid for the property name of a javascript object. For example



var b = {}
b['-^colour'] = blue; // Works fine in Firefox, Chrome, Safari
b['colour'] = green; // Ditto
alert(b['-^colour']); // Ditto
alert(b.colour); // Ditto
for(prop in b) alert(prop); // Ditto
//alert(b.-^colour); // Fails (expected)


This post details valid javascript variable names, and '-^colour' is clearly not valid (as a variable name). Does the same apply to object property names? Looking at the above I'm trying to work out if




  1. b['-^colour'] is invalid, but works in all browsers by quirk, and I shouldn't trust it to work going forward


  2. b['-^colour'] is completely valid, but it's just of a form that can only be accessed in this manner - (it's supported so Objects can be used as maps perhaps?)


  3. Something else




As an aside, a global variable in javascript might be declared at the top level as



var abc = 0;


but could also be created (as I understand it) with



window['abc'] = 0;


the following works in all the above browsers



window['@£$%'] = bling!;
alert(window['@£$%']);


Is this valid? It seems to contradict the variable naming rules - or am I not declaring a variable there? What's the difference between a variable and an object property name?


More From » javascript

 Answers
5

Yes, objects can be used as maps, and any string can be a property name. As you've discovered, some properties can only be accessed using the bracket syntax.



window['abc']


is accessing a property. It is not a variable, even though it refers to the same value (at the global level) as:



abc

[#96637] Thursday, May 27, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
herman

Total Points: 110
Total Questions: 90
Total Answers: 108

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
;