Javascript alert number starting with 0

javascript

I have a button where in the code behind I add a onclick and I pass a unique ID which will be passed to the js function. The id starts with a 0.

It wasn't working and eventually I figured out that the number, id, it was passing was wrong…

Ie. see this: js fiddle

It works with a ' at the start and end of the number. Just wondering why 013 turns to 11. I did some googling and couldn't find anything…

Cheers

Robin

Edit:

Thanks guys. Yep understand now.

As in this case the 0 at the start has a meaning, here the recipient ID in a mailing list, I will use '013' instead of just 013, i.e. a string. I can then split the values in js as each of the 3 values represents a different id which will always be only 1 character long, i.e. 0-9.

Best Answer

A numeric literal that starts with a 0 is treated as an octal number. So 13 from base 8 is 11 in base 10...

Octal numeric literals have been deprecated, but still work if you are not in strict mode.

(You didn't ask, but) A numeric literal that starts with 0x is treated as hexadecimal.

More info at MDN.

In your demo the parameter is called id, which implies you don't need to do numerical operations on it - if so, just put it in quotes and use it as a string.

If you need to be able to pass a leading zero but still have the number treated as base 10 to do numerical operations on it you can enclose it in quotes to pass it as a string and then convert the string to a number in a way that forces base 10, e.g.:

something('013');

function something(id){    
    alert(+id);             // use unary plus operator to convert
    // OR
    alert(parseInt(id,10)); // use parseInt() to convert        
}

Demo: http://jsfiddle.net/XYa6U/5/