RSS

Monthly Archives: October 2011

Strings and numbers in javascript – a hall of mirrors

One of my colleagues came across an interesting idiosyncracy when coding in javascript today. Consider the following script:

<script type="text/javascript">
    alert("1" - 1);
    alert("1" + 1);
</script>

What would you think that the first alert would display? For starters it would be best to throw an error (in my opinion anyway), but in reality, “1” is convert to an int and decremented by 1, which is fine.

The second alert, however, is a different story. Would you expect it to convert “1” to an int and add 1, in a simlar fashion to the first alert? No. In actual fact the int on the right-hand side of the expression is converted to a string and concaternated onto the “1”, resulting in “11”. Bizarre. This is because of ‘ambiguities in the + operator when dealing with strings’ I’m told.

I imagine this has already confused the hell out of a lot of web developers. However, it’s unlikely that it will be changed, because it would screw up so many web sites.

 
1 Comment

Posted by on October 26, 2011 in Uncategorized