3

I was playing around with eval and noticed that it can evaluate non-strings in Chrome, Firefox and Opera:

eval(Array) === Array; // true
eval(this) === this;   // true
eval(4 * 3 / 2) === 6; // true

Is this a standard behavior? Is it documented anywhere? I can't find any mention of eval taking anything other than a string argument.

If this isn't a standard behavior, can someone identify host environments where this doesn't work?

Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141

1 Answers1

5

Without a string, the code is already evaluated at a lower level, namely before it is passed to eval (e.g. your last statement is just doing eval(6)). That's the case for any function; it's how JavaScript code is evaluated. eval is not magical in that sense because it's "just" a function that "just" accepts an argument.

What eval should return when am expressions is passed that is not a string is described in the specification:

1. If Type(x) is not String, return x.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • Yeah, I just found that. I had no idea `eval` worked like that. – Dagg Nabbit Mar 10 '12 at 17:22
  • +1 You beat me to it. Also wanted to mention that if x is not a string, it just returns x – MMM Mar 10 '12 at 17:24
  • I don't suppose there's any reason to actually *use* `eval` like this, is there? – Dagg Nabbit Mar 10 '12 at 17:29
  • @GGG: Indeed there's not, since `eval` is plainly a noop this way. I guess there isn't a reason to use `eval` with a string either due to its security issues. – pimvdb Mar 10 '12 at 17:31
  • @pimvdb apparently there are useful [corner cases](http://stackoverflow.com/questions/9642491/getting-a-reference-to-the-global-object-in-an-unknown-environment-in-strict-mod/9647292#9647292) for regular `eval`... – Dagg Nabbit Mar 10 '12 at 17:32