This is to do with JavaScript's +
in operator - if a number and a string are "added" up, the number is converted into a string:
0 + 1; //1
'0' + 1; // '01'
To solve this, use the +
unary operator, or use parseInt()
:
+'0' + 1; // 1
parseInt('0', 10) + 1; // 1
The unary +
operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt()
is self-explanatory (converts into number, ignoring decimal places).
The second argument is necessary for parseInt()
to use the correct base when leading 0s are placed:
parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what
There's also parseFloat()
if you need to convert decimals in strings to their numeric value - +
can do that too but it behaves slightly differently: that's another story though.