Search code examples
syntax-erroreval

Why this expression throws an error?? eval("{'x': gridSize, 'y':gridSize}")?


i was messing around with eval, but stumbled across this error:

VM153:1 Uncaught SyntaxError: Unexpected token ':' at :2:1

the code is:

var gridSize = 20; eval("{'x': gridSize, 'y':gridSize}")

what is happening here???

I was expecting the vm to compile it, since if you remove the quotation marks around the expression it works


Solution

  • eval() takes a statement sequence. So something like eval('{x: 10}') will be syntatically correct, but does not do anything. It is a block consisting of a labeled statement.

    If you do eval("({'x': 10})"), that will return an object with a x property.

    It's not common to use eval though! Also, interestingly, eval returns the value of the last expression statement...