Thursday, July 31, 2008

JavaScript casting from string to numeral -- The 0 trick

Try this in the location bar of your browser (this will run the statements through the JavaScript implementation of your browser and write the evaluated value as a new document):

javascript: typeof("17" - 0)

This type casts the string "17" to the number 17. Your result will be number.


javascript: typeof("17" + 0)

will type cast the number 0 to the string "0" and will concatenate it to the string "17", so you will get "170". Your result will be string.


This looks like a thing that can result in bugs in implementations.

1 comment:

  1. That's why I think it's better to use "parseInt" and "toString".