Searching the Void in Javascript

What is void and does it have a role in modern Javascript?

The unary void operator is rather strange and has quirky use cases. Or, should I say ‘had quirky use cases’.

Primarily, void was used to check the true undefined. Consider the below code -

undefined = 0;
console.log("undefined: ", undefined);

The above code would return 0 instead of undefined a couple of years back.

So, we did this instead -

let planet;

//.. a lot of code ..

planet = void 0;
console.log("planet: ", planet);
// undefined

void was a sure way to find the true undefined.

Nowadays though, undefined cannot be reinitialized. So, just go ahead and use undefined whenever you want undefined.

const planet;


// more code

let planet = undefined;

There is, however, a different function of void.

Void in IIFE

We have talked about Immediately Invoked Functional Expression (IIFE) before. Consider below code -

const x = 1;
const y = 5;
let sum;

(function() {
  sum = x + y;
})();

console.log(sum);
// 6

We execute the function with no name when we come to it. Though this works, the syntax is a bit strange for people from non-Javascript worlds (those still exist).

const x = 1;
const y = 5;
let sum;

void (function() {
  sum = x + y;
})();

console.log(sum);
// 6

It is thus that void takes its rightful place, which still amounts to nothing (I cannot tell good jokes).

PS: Technically, you can remove brackets immediately after void, but my prettier thinks that is not as pretty.

comments powered by Disqus