I’m currently reading the book Functional JavaScript: Introducing Functional Programming with Underscore.js
Early on in the first chapter, I’ve stumbled upon an awesome line of code which is beautiful in its simplicity and effectiveness. One of the foibles of Javascript is that you have to test for both null values and the undefined value. The following function does that in one sweet line of code:
function existy(x) {
return x != null
};
If x equals undefined, the interpreter will see that it has two values with different types on each side of the != operator. So, it will use type coercion and cast both sides to a boolean value. As null and undefined are both falsey, the function returns false. That is, it is false to say that false does not equal false!
The only problem with it is the name. I’m not really sold on existy. So whenever I use that function, it will be called extant. It can be used as follows:
extant(null);
//=> false
extant(undefined);
//=> false
extant({}.notHere);
//=> false
extant((function(){})());
//=> false
extant(0);
//=> true
extant(false);
//=> true
The thing I love about that function is that it abstracts away the annoyance of checking for undefined and null into one short and sharp function-call. Admittedly, I tended to test for undefined more than null, as null is something typically set by developers, whereas undefined is set by the environment. But still, it’s a lot nicer than:
if(typeof someVariable === 'undefined')
0 Comments.