8
var @foo = 'bar';
// SyntaxError: missing variable name.

{ '@foo' : 'bar' };
// SyntaxError: invalid label.

var obj = { '@foo' : 'bar' };
obj.@foo;
// TypeError: can't convert AttributeName to string

var obj = { '@foo' : 'bar' };
obj['@foo'];
// "bar"

Can anyone explain to me why the '@' symbol is not allowed to be used in variable names and what I should be using it for?

idbehold
  • 16,833
  • 5
  • 47
  • 74
  • it is used in e4x some special kind of syntax to traverse xml – philipp Jan 21 '13 at 16:17
  • As well as you can't use `#`, `'` or `"`. It is invalid syntax for variable names. – VisioN Jan 21 '13 at 16:17
  • possible duplicate of [A question about JavaScript object property name](http://stackoverflow.com/questions/5006049/a-question-about-javascript-object-property-name) – jbabey Jan 21 '13 at 16:22

1 Answers1

7

It's not reserved or special, it's just not a valid javascript identifier character. For the same reason this works:

var obj = { 'foo-baz' : 'bar' };
obj['foo-baz'];

And this does not:

var obj = { 'foo-baz' : 'bar' };
obj.foo-baz;

Valid javascript identifiers must start with a letter or $, and may only contain letters, numbers, $, and _. Anything else in a property name will force you to use bracket notation.

Related question.

Community
  • 1
  • 1
jbabey
  • 45,965
  • 12
  • 71
  • 94
  • Okay, that makes sense. However, I know that the `-` symbol subtracts. What does `@` do? – idbehold Jan 21 '13 at 16:39
  • 2
    @idbehold it has nothing to do with what the symbol does (`@` has no special meaning in javascript, if you're curious) - according to the [spec](http://ecma262-5.com/ELS5_HTML.htm#Section_11.1.5), object keys must be either string literals, numeric literals, or identifier names. Since `@`, `-`, etc, are not allowed in identifier names, they must be wrapped in quotes to become string literals. – jbabey Jan 21 '13 at 16:41
  • Thank you, sir. Perfect explanation. – idbehold Jan 21 '13 at 16:47