Alexander Mills
Alexander Mills

Reputation: 100000

Why does JS eval() return only the value of an object

If I do this:

var x = eval('{a:"b"});
console.log(x); // -> "b"

all I get is the value in the object ("b"), not the key/property, or the whole object itself, which is weird.

but when I do this:

var x = eval('(function self(){return {a:"b"}})()');
console.log('x'); //  -> {a:'b'}

now it seems to give me what I would expect, the whole object. But why is this? Why do I need to wrap it in a (self-executing) function?

I am thinking of using eval to create some objects from strings, but need to know better how this works.

Upvotes: 2

Views: 1269

Answers (1)

zerkms
zerkms

Reputation: 254916

That's because {a:"b"} statement as-is represents the following:

  1. A code block delimited by { ... }
  2. A label a:
  3. A string literal "b"

The latter being the only expression produces the result.

And the same in the AST explorer: https://astexplorer.net/#/gist/909bebf...

To return an object you need to turn it into an expression first, like: wrap it in parentheses: eval('({a:"b"})')

But the whole idea of "I am thinking of using eval to create some objects from strings" sounds suspicious.

Upvotes: 4

Related Questions