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 -
|
|
The above code would return 0 instead of undefined a couple of years back.
So, we did this instead -
|
|
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.
|
|
There is, however, a different function of void.
Void in IIFE
We have talked about Immediately Invoked Functional Expression (IIFE) before. Consider below code -
|
|
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).
|
|
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.