Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Object Literals: Property names as strings vs. "raw"

Tags:

javascript

Can there ever be a difference between:

var x = {
  hello: 'world'
};

and

var x = {
  'hello': 'world'
};

?

That is, under what conditions does giving a property name as a string have different results than giving it as a "raw" name? For example, I know that var x = {}; x['@£$%'] = 'bling!'; is valid (since any string can be a property), but x.@£$% = 'bling!' won't work. Neither will language keywords or reserved keywords as property names (so var x = {for: 'good', class: 'y'}; won't work.

Anything else?

For example, what if

var hello = 'goodbye'; 

is defined in the above example? Or something else, like

function hello() { 
  return 'goodbye';
}

?

Should I always make my property names strings, just to be safe?

like image 727
ras Avatar asked Apr 26 '11 02:04

ras


2 Answers

I almost never specify anything beyond a-zA-Z as my key so I don't really worry about characters such as @. If for whatever reason you really need these characters, then sure go ahead and use quotes.

If you are sure the key word is a reserved word or even remotely think it may be, just wrap it in quotes and be safe .. otherwise just go quoteless and save typing time.

A variable with the same name as your key has absolutely no bearing because it's taken literally.

var hello = 'god';
({hello:2})['hello'] // 2
like image 123
meder omuraliev Avatar answered Oct 26 '22 19:10

meder omuraliev


In an object literal, you can use either a string literal (quoted) or an identifier (unquoted). In the first case, you can therefore use whatever characters you like, while in the second, you have to follow the rules for identifiers laid out in the ECMAScript spec. The same identifier rules apply when using the dot notation property accessor. Simplified summary:

  • The identifier must start with a letter, _ or $ (both of which may also appear anywhere in the identifier)
  • After the first character, more characters are allowed, including numbers
  • The identifier must not be a reserved word (new, var, function, delete, etc)
like image 30
Tim Down Avatar answered Oct 26 '22 19:10

Tim Down