Wednesday, November 12, 2014

Today I learned: void in JavaScript

Reading stuff about the JavaScript Module Pattern, about self-invoking anonymous functions (Tweet by Paul Irish , by the way, this tweet made me sign up to Twitter once again), I stumbled about undefined.

I knew that undefined was different. I knew that it was not a keyword. So what is it?
It's an variable. And a value.

It's a global variable, a property of the the global object, in the browser window.undefined.

I stumbled upon the the Mozilla documentation about undefined. As an alternative to
if (typeof lorenz === 'undefined')
they presented
if (lorenz === void 0)

I wondered. What's this void operator?
As the documentation succinctly explains:

The void operator evaluates the given expression and then returns undefined.
That's all. And then I remembered where I saw this weird little friend last time. It was about 1999 and it was about here:

<a href="javascript:void(0)" onclick="mouseOver()"><img src="earth_rotating.gif" /></a>

We've come a long way, baby. I'm glad we don't have to code this way any longer.

Anyway, now I think about a proper use case for this operator.

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai

    ReplyDelete