I have come across this code:
return someFunctionThatReturnsAnArray()
.map((action) => void dispatch(action))
.run();
Can anyone suggest why you would prefix void
in the map function so that it returns undefined
each time?
I have come across this code:
return someFunctionThatReturnsAnArray()
.map((action) => void dispatch(action))
.run();
Can anyone suggest why you would prefix void
in the map function so that it returns undefined
each time?
This is essentially a clever way of defining a function that returns undefined
.
From MDN:
The void operator evaluates the given expression and then returns undefined.
Your code is essentially the same as:
return someFunctionThatReturnsAnArray()
.map((action) => { dispatch(action); })
.run();
I'll be honest: if I came across that code in any project that I work with, I'd flag it for review. It doesn't really make sense and is potentially confusing.
void
operator allows evaluating expressions that produce a value into places where an expression that evaluates to undefined is desired.
So it looks like :
dispatch
method is called, its return value is not importantmap
method is an array with undefined
values but its length is equal to the number of dispatched callsrun
method is not standard for the Array prototype (seems like a custom patch), therefore it is hard to tell what it does.One of its usage would be info of dispatched calls
Array.prototype.run = function() {
console.log("Dispatched calls : " + this.length);
};
var getArray = function() {
return ['1', '2', '3'];
}
var dispatch = function(n) {
return 10*n;
}
getArray().map((action) => void dispatch(action)).run();
Taken from https://eslint.org/docs/rules/no-void
The void operator takes an operand and returns undefined: void expression will evaluate expression and return undefined. It can be used to ignore any side effects expression may produce:
The common case of using void operator is to get a “pure” undefined value as prior to ES5 the undefined variable was mutable:
// will always return undefined (function(){ return void 0; })(); // will return 1 in ES3 and undefined in ES5+ (function(){ undefined = 1; return undefined; })(); // will throw TypeError in ES5+ (function(){ 'use strict'; undefined = 1; })();
Another common case is to minify code as void 0 is shorter than undefined:
foo = void 0; foo = undefined;
When used with IIFE (immediately-invoked function expression), void can be used to force
the function keyword to be treated as an expression instead of a declaration:
var foo = 1; void function(){ foo = 1; }() // will assign foo a value of 1 +function(){ foo = 1; }() // same as above function(){ foo = 1; }() // will throw SyntaxError
Some code styles prohibit void operator, marking it as non-obvious and hard to read.
Can't see any good reason to be using it in the snippet that you have provided.