0

evaling a string that declares an array with functions works fine. However, evaling a string that declares an object with functions does not work. Can anyone tell me why?

This JSFiddle and the following code demonstrate the problem:

"use strict";

// functions in arrays are ok:
var x = "[ function() {}, [function() {}] ]";
var o = eval(x);
console.log(o[1]);

// functions in objects are not ok (for some reason):
var y = "{a: function() {}, b: [function() {}] }";
var o = eval(y);
console.log(o['a']);

Only the second eval causes trouble.

In Chrome, I get:

Uncaught SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function.

In IE 11, I get:

Expected identifier

Domi
  • 22,151
  • 15
  • 92
  • 122
  • http://stackoverflow.com/questions/9943278/javascript-eval-expression , http://stackoverflow.com/questions/4305003/why-eval-fails-here , http://stackoverflow.com/questions/10791202/javascript-eval-return-behavior?lq=1 , http://stackoverflow.com/questions/3360356/why-the-open-quote-and-bracket-for-eval-jsonstring-when-parsing-json – user2864740 Apr 15 '14 at 19:53

1 Answers1

1

The problem isn't where you think it is.

Change

var y = "{a: function() {}, b: [function() {}] }";

to

var y = "({a: function() {}, b: [function() {}] })";

Or change the call to eval to

var o = eval('('+y+')');

to avoid eval thinking you pass a block instead of an object.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • So, if I want to `eval` an rvalue rather than code, I should wrap it in "()"? Is there any downside to that? – Domi Apr 15 '14 at 19:46
  • @Domi It has nothing to do with "rvalues", simply about parsing - it is "code" in both cases. When *not* in an Expression context, `{..}` is *not* treated as an Object Literal but rather as a Block Statement. Parenthesis are the easiest (and probably most understood/consistent) way to ensure an Expression context, but not the only way. – user2864740 Apr 15 '14 at 19:47
  • @user2864740 Do you have a link or some more information on this? I'd be interested in alternatives, as well as pros and cons of different "`eval`ing strategies". And FYI: an [rvalue](http://en.wikipedia.org/wiki/Value_(computer_science)) is a certain kind of expression, the kind of expression I am operating with here. – Domi Apr 15 '14 at 19:52
  • @Domi I've added some related questions on the post (see the ["Why the .. bracket.."](http://stackoverflow.com/questions/3360356/why-the-open-quote-and-bracket-for-eval-jsonstring-when-parsing-json?lq=1)). The [ES5 grammar rules](http://es5.github.io/#A) contain the information, but need some reading. – user2864740 Apr 15 '14 at 19:54