Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, eval(010) returns 8 [duplicate]

Tags:

javascript

If I use the code:

string = '010';
write = eval(string);
document.write(write)

I get 8 written on the page. Why? This happens even if 010 isn't a string.

like image 1000
Some Guy Avatar asked Jul 16 '11 14:07

Some Guy


People also ask

What does eval return in JavaScript?

eval() returns the completion value of statementsFor if , it would be the last expression or statement evaluated. The following example uses eval() to evaluate the string str .

What will be the result of JavaScript 10?

Why in JavaScript does 10 === 010 result in false - Stack Overflow.

How do you find the value of eval?

The eval is a part of the JavaScript global object. The return value of eval() is the value of last expression evaluated, if it is empty then it will return undefined . Example: eval("console.

Is it safe to use eval in JavaScript?

Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!


2 Answers

Because 010 is parsed as octal. Javascript treats a leading zero as indicating that the value is in base 8.

Similarly, 0x10 would give you 16, being parsed in hex.

If you want to parse a string using a specified base, use parseInt:

parseInt('010', 8); // returns 8.
parseInt('010',10); // returns 10.
parseInt('010',16); // returns 16.
like image 171
developmentalinsanity Avatar answered Oct 03 '22 09:10

developmentalinsanity


Prefixing a number with an 0 means it's octal, i.e. base 8. Similar to prefixing with 0x for hexadecimal numbers (base 16).

Use the second argument of parseInt to force a base:

> parseInt('010')
8
> parseInt('010', 10)
10
like image 33
phihag Avatar answered Oct 03 '22 09:10

phihag