When writing arrow functions that shouldn't return any value you may be tempted to return an ||
operation such as:
/* Leaking Arrow Function */
const arrowThatShouldntReturn = () => someOtherFunction() || undefined;
This may work if someOtherFunction
returns a falsy value, but won't work for truthy values.
The Void Operator
The void
unary operator evaluates the given expression and then returns undefined. You'll see this operator used all over the React codebase to create non-leaking arrow functions!
To use it we can define our functions as:
/* Non-leaking Arrow Function */
const arrowThatShouldntReturn = () => void someOtherFunction(); // returns undefined
Or when we don't wish to do anything yet:
/* Non-leaking Arrow Function */
const arrowThatShouldntReturn = () => void; // returns undefined
The first method will evaluate someOtherFunction()
and return undefined regardless of the returned value. The second method is equivalent to void undefined
which evaluates undefined
and returns undefined
.
Are there other use cases? Yes.
Before ES6
In old times you used to define variables using var
. This immediately adds the variable you're declaring to the global object. It also pretty much didn't have restrictions, so you could just var undefined = true
and it'd work. This is one of the reasons void 0
used to be the preferred method. There's even an ESLint rule for it! It's not necessary in strict environments though.
HTML
You probably also met the void operator in anchor tags! Ever met this bad boy?
<a href="javascript:void(0)"/>
Yup, that's it. We used it to pretty much create links that preventDefault.
IIFE
You can use it with IIFEs too!
(function() { return true })(); // returns true
void function() { return true }(); // returns undefined
If you liked this article don't forget to love this post! If you found any issues with this article or have questions don't hesitate to comment them! Thanks for reading! You can follow me on Twitter, or read more of my content here or on my personal blog!
Top comments (0)