What is the standard for an object in javascript?

{id:1,name:'test'}

or

{'id':1,'name':'test'}

I saw that they both used many times, and now I'm embarrassed!

+3
source share
6 answers

In JavaScript, the two methods are almost equivalent, you can use both options, but with the version without the quotes you cannot define properties with the names of reserved keywords, for example:

// valid
var obj = {
  'for': 'test'
};

// SyntaxError
var obj = {
  for: 'test'
};

This is why the JSON standard allows only quoted keys to be used by specification .

Edit: Ok, now let's see why.

Grammar Object initializer is defined as follows:

ObjectLiteral:
    {}
    { PropertyNameAndValueList }

PropertyNameAndValueList :
    PropertyName : AssignmentExpression 
    PropertyNameAndValueList , PropertyName : AssignmentExpression 

PropertyName :

PropertyName :
    Identifier 
    StringLiteral 
    NumericLiteral

, , Word, :

7.5.1 Reserved Words
Description

Reserved words cannot be used as identifiers.

Identifier:

Identifier ::
    IdentifierName but not ReservedWord
+11

, , , , .

, /.

+3

, JSON.

+3

, , . :

var o = { 'id': 1, name: 'test'}

( , ).

:

alert(o.id);
alert(o['name']);

, , , , , , .

+2

, , . , .

+1

, , . , ECMAScript , . -, . ,

break
do
instanceof
typeof 
case
else
new
var 
catch
finally
return
void 
continue
for
switch
while 
debugger
function
this
with 
default
if
throwdelete
in
try

, . :)

class
enum
extends
super
const
export
import

To be safe and not need to look for specifications every time, I would say that it is better to specify your identifiers. To really see the problem, check them out in Safari, at least in version 4.0.4, when you use any of these keywords as identifiers. For example, try the following:

var class = "my class";

Will not work in a simple declaration or inside a declaration of an object of type JSON:

var myObject = {
    goodProperty: "this works",
    class: "gimmeh the errarz codez!",
};
0
source

Source: https://habr.com/ru/post/1728575/


All Articles