Note that there are some explanatory texts on larger screens.

plurals
  1. POValid javascript object property names
    text
    copied!<p>I'm trying to work out what is considered valid for the property name of a javascript object. For example</p> <pre><code>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) </code></pre> <p>This <a href="https://stackoverflow.com/questions/1661197/valid-characters-for-javascript-variable-names">post</a> 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</p> <ol> <li><p>b['-^colour'] is invalid, but works in all browsers by quirk, and I shouldn't trust it to work going forward</p></li> <li><p>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?)</p></li> <li><p>Something else</p></li> </ol> <p>As an aside, a global variable in javascript might be declared at the top level as</p> <pre><code>var abc = 0; </code></pre> <p>but could also be created (as I understand it) with </p> <pre><code>window['abc'] = 0; </code></pre> <p>the following works in all the above browsers</p> <pre><code>window['@£$%'] = "bling!"; alert(window['@£$%']); </code></pre> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload