Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 882
Pablo Matias Gomez Avatar asked Jan 30 '26 06:01

Pablo Matias Gomez


1 Answers

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.

like image 192
agconti Avatar answered Jan 31 '26 20:01

agconti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!