I am trying to pass a number to my JavaScript function, but actually a wrong value is getting passed. I am giving the entire code here:
<html> <head> <script type='text/javascript'> function test(num) { /*It should alert as 01004 or 1004 but to my surprise it's alerting as 516!*/ alert(num); } </script> </head> <body> <a href='javascript:test(01004);'>Test it!</a> </body> </html>
In the above code, instead of 01004, if I pass it as 10040 I am getting the correct value in the alert box.
Any idea about this strange case?
Thanks in advance.
A numeric literal that starts with a zero is interpreted as octal, so writing 01004 is exactly the same as writing 516.
Some other answers suggesting using parseInt inside the function to convert the octal value to decimal.
This wont help, as the numeric value 516 is passed to the function. If you ask parseInt to give you a base 10 interpretation back, you’ll get 516!
The way to fix this is either to lose the leading zero, or if the zero is required, make it a string literal rather than a numeric, and use parseInt(num, 10) inside the function.