Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `eval` work on non-strings?

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?

like image 934
Dagg Nabbit Avatar asked Aug 12 '26 04:08

Dagg Nabbit


1 Answers

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.

like image 200
pimvdb Avatar answered Aug 13 '26 18:08

pimvdb