Thursday, November 13, 2014

Today I learned: There is a use for void

Today, I learned two use cases for the Operator void
For the sake of Repetition: void is an operator which evaluates the given expression and returns undefined.

So, I asked myself, what could be modern day use cases for this operator?

I think there is no reason to be paranoid about undefined hijacking (i.e. setting the property undefined to something else than the value undefined.) Since ES 5, this is not allowed. And modern browser won't throw an Error in your face, when you do something like undefined = 5; but silently ignore your crappy code.

The other use, using it in the href attribute of a tags, is heavily discouraged today. In my questions on Google Plus and reddit, where I asked what sense people made out of the void operator, giving and old example of setting it into the href attribute, there were comments, begging not to do this.

So, finally, here the solution: first of all, you could use bookmarklets. What is a bookmarklet? Type javascript:3+7; in your browser's URL bar. Make sure, you use Firefox or IE (have it tested only in FF) to see the result. Congrats! You have executed your first bookmarklet. You can save this ingenious script to your bookmarks. What did it do? It evaluated 3+4 and changed your current page to that value. That's why you saw 7 in your browser. Webkit browsers don't do that, by the way. Never.

So void to the rescue: just type javascript:void(3+4) and nothing will be redirected. So you can implement a word counter bookmarklet.


Another use are minifiers.
Just like Yury Trabanko replied to me on Google+:



Minifiers use void operator. For example
function() {
    if(isA()) {
        return doB();
    }
    doC();
}


will become
function(){
    return isA()?doB():void doC();
}

Happy coding to you all!

No comments:

Post a Comment