30 Jan
Posted by krisgale as javascript, annoyances, browsers
here’s an interesting javascript ‘gotcha’… this block of code:
var y = 37;
var x = parseInt(y,10);
var s = “37″;
alert(x === s);
gives you a “false” alert box, whereas this:
var y = 37;
var x = “” + parseInt(y,10);
var s = “37″;
alert(x === s);
yields “true.”
apparently, ‘x’ is not able to be compared to other strings until it is concatenated with another string, or implicitly converted to one using Object.toString().
| bookmark it! | ||||||
|
2 Responses
Jay Moiron
January 30th, 2008 at 8:43 pm
1Actually, JavaScript has types; they’re just weak because there are some implicit conversion rules. In this case, any use of binary + involving a string results in the string representation of each side being concatenated. Firing up firebug quickly shows:
>>> “10″ + 5
“105″
>>> 10 + “5″
“105″
>>> 10 + 5
15
Not only that, but you’re using ===, which is the “Strict Equals Operator”, as opposed to the “Equals Operator”. EMCA-262 sections 11.9.3 and 11.9.6 spell out the specific differences between === and ==, but you can think of == as a “type coerced equivalence” and === as a “strongly typed equivalence”:
http://www.ecma-international.org/publications/standards/Ecma-262.htm
Just as JavaScript will coax integers to strings to concatenate rather than add (I believe Perl will do this based on the order of the operands), it’ll attempt to do a string compare between two objects if you use “==”.
– Jay
krisgale
January 30th, 2008 at 9:57 pm
2hmm, i hadn’t thought of === in that way but you’re right. it’s just that it’s typical use is to ensure that you’re comparing the actual contents of one string to another, not some evaluated representation of it (”03″ == 3). i guess the only way to be 100% sure is to always use Object.toString() and === when comparing strings, or Object.valueOf() and == when comparing non-strings.
RSS feed for comments on this post · TrackBack URI
Leave a reply
Categories
Archives
Links
Meta
Calendar