Saturday 13 June 2015

The void Operator in JavaScript

The other day, while checking the source of underscore.js (I already mentioned time ago that it was a really beautiful code to learn from) it came to my attention some code like this:

return obj == null ? void 0 : obj[key];

That void operator, what is it useful for? (both in general and in this particular case). Checking in MDN, for this particular use you'll find this:

The void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

So it's being used to safely assign the undefined value. "safely" means that when we use undefined this way: obj = undefined; you are using the undefined global property, that by default points to the undefined value, but that someone could have changed assigning it another value and breaking your code!

However, if you run this code in firebug:

var a = undefined;
undefined
a === undefined;
true
undefined = "xxx";
"xxx"
a === undefined;
true

You'll see that indeed the attempt to change the value of the undefined property has not worked! As usual, MDN has the explanation:

undefined is a property of the global object, i.e. it is a variable in global scope. The initial value of undefined is the primitive value undefined.
In modern browsers (JavaScript 1.8.5 / Firefox 4+), undefined is a non-configurable, non-writable property per the ECMAScript 5 specification. Even when this is not the case, avoid overriding it.

The reference for the void operator mentions another use case that really confused me:

When using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration.

So they propose creating IIFS's like this: void function(){}();
I see no use at all in creating an IIFE like that. I pretty much prefer the "normal style":
(function(){}());
or
(function(){})();
Using void adds nothing other than confusion and it looks to me as if we were in another language declaring that the function returns nothing.

Trying to understand if I were missing something with this I checked what seems to be the seminal article about IIFE's. There the author mentions some other utterly confusing ways to declare a IIFE, like these:

// If you don't care about the return value, or the possibility of making
// your code slightly harder to read, you can save a byte by just prefixing
// the function with a unary operator.
!function(){ /* code */ }();
~function(){ /* code */ }();
-function(){ /* code */ }();
+function(){ /* code */ }();

As the author says, it makes the code harder to read, for sure. I love how expressive and freak javascript is, but things like this seem utterly unnecessary to me.

No comments:

Post a Comment