Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the '@' symbol reserved in javascript and what is its purpose?

Tags:

javascript

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?

like image 896
idbehold Avatar asked Jan 21 '13 16:01

idbehold


People also ask

What does $() mean in JavaScript?

Usually when you encounter $() , that means the developer is using a javascript library, such as jQuery. The $ symbol is the namespace for those libraries. All the functions they define begin with $. , such as $. get() .

Why is symbol used in JavaScript?

Symbols are often used to add unique property keys to an object that won't collide with keys any other code might add to the object, and which are hidden from any mechanisms other code will typically use to access the object. That enables a form of weak encapsulation, or a weak form of information hiding.

Is event a reserved word in JavaScript?

Then it works fine. My conclusion is 'event'is a reserved word which stands for event argument in Java Script.

What is identifier in JavaScript?

An identifier is a sequence of characters in the code that identifies a variable, function, or property. In JavaScript, identifiers are case-sensitive and can contain Unicode letters, $ , _ , and digits (0-9), but may not start with a digit.


1 Answers

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.

like image 120
jbabey Avatar answered Sep 21 '22 14:09

jbabey