Veera
Veera

Reputation: 33182

JavaScript function parameter

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.

Upvotes: 1

Views: 2261

Answers (4)

bobince
bobince

Reputation: 536369

Congratulations, you are the one millionth customer to get tripped up by octal literals in a language descended from B (and hence C).

Your prize is to lead the pitchfork parade outside Ken Thompson's house.

Upvotes: 1

tanathos
tanathos

Reputation: 5606

Quote the number -> '01004'

EDIT: I see parseInt('01004', 10) works fine... I really don't know why parseInt(01004, 10) doesn't

EDIT2: Ok, thanks to Paul Dixon

Upvotes: 0

Paul Dixon
Paul Dixon

Reputation: 300835

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.

Upvotes: 10

Hank Gay
Hank Gay

Reputation: 71939

The leading zero is probably making it think the number is octal.

UPDATE: Thanks to @Paul Dixon for jogging my mind awake somewhat this morning. 01004 is a literal, so no amount of after-the-fact parsing, i.e., parseInt, is going to update the base of the number. You need to either strip the leading 0 in your code to make it 1004 (the easiest solution), or put quotes around the literal to make it a string before sending it to parseInt (which is more work for no reason I can see).

Upvotes: 6

Related Questions