Sunday 12 March 2017

Why does JS eval() return the value

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.



via Alexander Mills

No comments:

Post a Comment