Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quoted JS object property names when evaled do not work as expected [duplicate]

Tags:

javascript

Why does

eval('{pickup : new Date(2012, 7, 23, 15, 49, 0, 0)}')

work and

eval('{"pickup" : new Date(2012, 7, 23, 15, 49, 0, 0)}')

does not? I get

Uncaught SyntaxError: Unexpected token :
at <anonymous>:1:1

and yet

{"pickup" : new Date(2012, 7, 23, 15, 49, 0, 0)}

as an object works as expected.

like image 297
P Hemans Avatar asked Dec 05 '25 18:12

P Hemans


1 Answers

Because {} is interpreted as a block, not as an object literal, which makes pickup a label, not an object key. This is what Javascript sees:

{
  pickup: 
    new Date(2012, 7, 23, 15, 49, 0, 0);
}

If you want Javascript to see this as an object literal, assign it to something or otherwise make it an expression instead of a top-level statement.

like image 51
deceze Avatar answered Dec 08 '25 07:12

deceze