Skip to content Skip to sidebar Skip to footer

Is This Javascript Object Literal Key Restriction Strictly Due To Parsing?

Please refer to the code below, when I 'comment in' either of the commented out lines, it causes the error (in IE) of '':' expected'. So then is my conclusion correct, that this i

Solution 1:

The limitation of the literal object syntax is that the names has to be literal. As the names can be specified as an identifer as well as a string, it's not possible to use a variable instead.

This will create an object with a property n, not a property answer:

var n = 'answer';
var o = { n: 42 };

Solution 2:

You cannot use variables as keys when defining object with {}

Therefore they are being interpreted as string names and can consist only of characters avaliable for variable names

the

objectname[anythingThatReturnsValue]='value1'; is the way to go.

ALSO

You can generate a string and parse it

var s='{"'+keys.ONE+'": "value1"}';
var obj=JSON.parse(s);
//or
s='var obj2='+s;
eval(s);

Both above methods are bad practices for creating objects in JavaScript and I don't recommend them.

Solution 3:

Think about it: if it were to work the way you want it would totally introduce a language ambiguity.

var obj = {something:"red"}
var obj = {"something":"red"}

The two statements are equivalent in JavaScript, because bareword keys are "autoquoted." So if something means the literal string "something", how it could also refer to the variable "something". It can't. So if you want to use variables they have to go in square bracket notation instead of key : value notation.

Solution 4:

You can try:

var obj = {};
varval = 'foo';

obj[val] = 'bar'; 

obj.foo >>> 'bar';

Post a Comment for "Is This Javascript Object Literal Key Restriction Strictly Due To Parsing?"