Using void in JavaScript
Why and how?
A quick note on how and why the void keyword can be used in JavaScript. The word void is an operator in JavaScript. This operator allows you to insert expressions and always returns undefined.
Void for IIEFE
IIFE (Immediately-invoked function expression) — a self-calling function. Usually such functions are described as follows:
(function(arg){ expression })(arg)
!function(arg){ expression } (arg)
+function(arg){ expression } (arg)
But it is also possible to describe IIFE functions using void:
void function(arg){ expression } (arg)
The advantage of this entry is idiomatically. There is also a theory that the compiler processes such code faster, but this is not certain.
Void for the truly Undefined
In JS there is a special type undefined
, which is written the same way as the name and yet is not a keyword. So undefined can be overridden and substituted. Why this can be done is another question. But if you write void
instead of undefined
, it trivially allows you to make the entry a bit shorter and add idiomatically, allowing you to flesh out the void
. You can describe any expression after void
:
var foo = void 0;
let bar = void null;
let buz = void 'Some comment here';
I wrote about all the ways to get uncertainty in more detail in this post:
Void and Arrow functions
If you need to use the arrow function as a callback function that is not supposed to return anything, you can do so using void
. Using jQuery as an example, we could write using the arrow function in a modern way:
$(_=>void( ...somedo... ))
// But it's easier to write it like this
$(_=>{ ...somedo... })
It’s not the best example, but it gets the point across.
Void for automatically clear the temporary variable
Challenge: swap variable values. Unlike numbers, there are not many options with strings. Suppose we change using a temporary variable, but we want it to be cleared in the end. We can use void for this purpose:
let a = 'abc';
let b = 'cde';
let c = void(c = a, a = b, b = c)console.log(a, b, c);
// a = 'cde'
// b = 'abc'
// c = undefined
Puzzles with void
And a little trick question. What’s going to happen and why? :)
let x = void 'foo' + '!!!';
You can use void for shortener some messages, like this:
throw 'Argument is ' + void'' + '!'
Using void in JS for debugging
Daily Notes
setTimeout(void function(){ ... }, 1e3)
That’s how easy it is to prevent call a function. This can be used for debugging when the code block is large and it’s inconvenient to comment on it. I’ve used this case more often:
if (0) setTimeout(function(){ ... }, 1e3)
This case is more versatile and can be used to block different sections of code. Moreover, the case is universal for different programming languages.
Nevertheless, void also has the right to life and maybe you will find it more interesting and convenient.
Here’s a little tip for you. If you like it, please support me by giving me a “Like”. It’s important to me. 😻