So my understanding is that eval() can take a string that is a mathematical expression and return the value of the expression. Why is it then that adding a '0' before a number e.g. changing '11' to '011' changes the result?
Asked
Active
Viewed 283 times
-3
-
2`eval` doesn't take a "string that is a mathematical expression", it takes a string that is *JavaScript source code*. – hobbs Nov 19 '19 at 01:45
-
Type 011 on the JavaScript debug console – Adrian Brand Nov 19 '19 at 01:56
-
Using math.js, `math.eval()` will evaluate a math expression. https://mathjs.org/ – chiliNUT Nov 19 '19 at 03:10
-
On a side note, [you really shouldn't use `eval` unless you absolutely have to](https://stackoverflow.com/questions/18269797/what-does-eval-do-and-why-its-evil). – John Montgomery Nov 19 '19 at 18:21
1 Answers
2
Because 011
is an octal literal which is equal to decimal 9 (9 + 9 gives 18). Removing the 0
prefix makes the value decimal, so the result is decimal 11 (11 + 11 gives 22).
You can try it from a node REPL
> eval('011')
9
If you enable strict mode, it wont allow octal literals. related

Paul Rooney
- 20,879
- 9
- 40
- 61