This post was published on Thursday 15th of November 2007.
I've neglected my duties here for a while but here's a interesting snippet of JavaScript Boolean behavior before I resume normal service. It has to do with the behavior of the && operator when the first operand evaluates to true.
The story started when I was writing a unit test for a very simple function that looked something like this:
function f( ) {
return a && b;
}
I'm reasonably experienced in JavaScript and when I saw the function I expected it to always return a Boolean since, logically, the result of an && (AND) operation can only be true or false. I was wrong however because in the case that a evaluates to false it just returns the value of a and if it evaluates to true it returns the value of b! In code:
r = "" && true; // r = "" r = null && true; // r = null r = 0 && true; // r = 0 var UNDEF r = UNDEF && true; // typeof r = undefined r = true && ""; // r = "" r = true && null; // r = null r = true && 0; // r = 0 r = true && UNDEF; // typeof r = undefined
After my initial bafflement I can't really appreciate this curious feature. As far as I know it's so obscure or little known that if you would use it in this way practically noone would understand it just from reading the code. Take this for example:
function( a, b ) {
// a and b are strings
return (a && b).toUpperCase();
}
I'd probably raise an eyebrow if I saw something like that.
By the way, The ECMA Script specification explicitly mentions this in a note:
The value produced by a && or || operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.
Have something to say about this post? Share your thoughts!
This post was published on Thursday 15th of November 2007. The previous entry was "Visitor statistics & screen resolutions". The next entry is "JavaScript closures in for-loops".