0

I tried to evaluate string function toString() in console.
In one scenario it is working fine and in another scenario it is not working as expected.

Scenario 1:

eval(99.toString());

output:

Invalid or unexpected token ...

Scenario 2:

var a = 99;
eval(a.toString());

Output:

99

Please help me to understand the difference between both the scenarios.enter image description here

3 Answers3

1

That has nothing to do with eval.

The error is produced by 99.toString. The reason is that 99. is read as a number (equivalent to 99.0) and then toString is just a random word that doesn't fit the syntax:

99.0 toString  // what the parser sees

To fix it, you need to keep . from being treated as part of the number. For example:

99 .toString()    // numbers can't contain spaces, so '99' and '.' are read separately
(99).toString()   // the ')' token prevents '.' from being read as part of the number
99.0.toString()   // '99.0' is read as a number, then '.toString' is the property access
99..toString()    // same as above, just with '99.' as the number
99['toString']()  // using [ ] for property access, no '.' at all
melpomene
  • 84,125
  • 8
  • 85
  • 148
0

A numeric literall (99) is not and object with properties. A variable with value 99 like var x = 99 is and object and you can use methods like x.toString()

Jordi
  • 189
  • 6
-1

eval expects a script input (string), in example:

var x = eval('var a = 99; a.toString()');
console.log(x);
Alon Yampolski
  • 851
  • 7
  • 15