Pablo Matias Gomez
Pablo Matias Gomez

Reputation: 6813

Should Javascript Objects keys be quoted in?

I know there are some questions that may refer to this, but I didn't find anything related to javascript strictly.

For example this: JSON Spec - does the key have to be surrounded with quotes?

But my question is: should we use quotes when we write a Javascript Object?

I think it is more elegant to write is without quotes and also more readable, but is it OK?

For example when I use it to pass as an argument:

myFunction({
    "key": "value",
    "otherKey": 10
});


myFunction({
    key: "value",
    otherKey: 10
});

Also as I read, the second one works in every browser, unless it is a forbidden word (for, if, etc), so this wouldn't be a problem.

I think the second one looks better, but I also think it may not be a good practice..

I did this practice for years and now I am starting to think that I was wrong but I don't feel it good using quotes.. What should I do?

Upvotes: 3

Views: 2966

Answers (3)

maerics
maerics

Reputation: 156434

JavaScript does not require object literal keys to be quoted if they are valid identifiers.

All of the following object literal forms are equivalent in JavaScript (since the keys are always converted to strings by the interpreter):

var a = {foo: 1};
var b = {'foo': 1};
var c = {"foo": 1};

You must only quote the keys if they are not valid "identifiers", for example:

var nonIdentifierKeys = {
  '=)': 'special characters',
  '  ': 'whitespace',
  '42': 'numbers',
  // etc.
};

Note that JSON is derived from JavaScript object literal notation but it explicitly requires key names to be quoted (with double-quotes):

{"json":"must quote keys"}

Upvotes: 6

agconti
agconti

Reputation: 18103

Short Answer: JavaScript object keys do not need to be surrounded by quotes.

Because:

JSON and the object literal syntax in JavaScript are different things, although they are closely related.

JSON has to be transmitted as a string between the server and the client. Because of this, all the values need to be wrapped in "" so they can be tokenized, split, and reconstructed back into objects when they arrive.

The javascript literal syntax does not have to go through this transfer, and so the quotes are not necessary. Convention dictates that you do not use quotes unless the key has a space or is a special reserved word.

Upvotes: 6

plalx
plalx

Reputation: 43718

You do not have to quote keys, unless they aren't valid identifiers (e.g. they contain spaces or they are reserved words). The object literal syntax isin't the same as JSON. It's probably a simple matter of preference, but I only quote keys when required to do so.

Upvotes: 2

Related Questions