Using the void Operator to Avoid undefined in Arrow Functions
Many developers are familiar with the arrow function syntax in JavaScript, but few know about the void
operator trick to avoid undefined
values.
The Problem
When using arrow functions, it's common to return an object literal. However, if you don't wrap the object literal in parentheses, the JavaScript interpreter will throw a syntax error:
const foo = () => { bar: 'baz' }; // SyntaxError: Unexpected token :
To fix this, you can wrap the object literal in parentheses:
const foo = () => ({ bar: 'baz' }); // Works as expected
However, what if you want to return undefined
explicitly? You might try this:
const foo = () => undefined; // Doesn't work as expected
The problem is that the undefined
value is not actually returned. Instead, the function returns undefined
because it doesn't have a return statement.
The void
Operator Trick
This is where the void
operator comes in. The void
operator takes an expression as an argument and returns undefined
. You can use it to explicitly return undefined
from an arrow function:
const foo = () => void 0; // Returns undefined explicitly
In this example, void 0
is an expression that evaluates to undefined
. The 0
is arbitrary; you could use any value, as it will be ignored.
Example Use Case
Here's an example use case:
const cache = new Map();
const getFromCache = (key) => {
const value = cache.get(key);
return value === undefined ? void 0 : value;
};
console.log(getFromCache('missingKey')); // undefined
console.log(getFromCache('existingKey')); // Value associated with existingKey
In this example, the getFromCache
function returns undefined
explicitly using the void
operator when the key is not found in the cache.
Conclusion
The void
operator trick is a useful technique to have in your JavaScript toolkit. It allows you to explicitly return undefined
from arrow functions, which can be important in certain scenarios. By using void 0
, you can avoid the implicit undefined
value that can lead to unexpected behavior.