logo

NJP

Unexpected JavaScript...

Import · Jan 24, 2010 · article

imageEvery once in a while, I run across something completely unexpected in JavaScript. This morning was one of those times.In my code, I had the equivalent of this:

var x = 0;if ('' == x) gs.log('What the???');else gs.log('Ah, that was expected!');

Wanna take a guess which statement was logged?

In JavaScript, an empty string evaluates as equal to a zero. Doesn't make any sense to me, but apparently it made sense to a JavaScript designer. I suspect what's going on here is that the empty string is coerced to a number (which would be zero) and is then compared to the number 0 in variable x. What I expected was the opposite: that the number 0 would be coerced to the string '0', and the comparison would have evaluated to a false.

I fixed the code like this:

var x = 0;if ('' == '' + x) gs.log('What the???');else gs.log('Ah, that was expected!');

This forces the coercion to happen as I expected (and wanted) it to.

Another day, another oddity!

View original source

https://www.servicenow.com/community/in-other-news/unexpected-javascript/ba-p/2288235