This page looks best with JavaScript enabled

Searching the Void in Javascript

 ·   ·  ☕ 2 min read

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 -

1
2
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 -

1
2
3
4
5
6
7
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.

1
2
3
4
5
6
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 -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things