Function call prefix with void

I came across this code:

return someFunctionThatReturnsAnArray()
  .map((action) => void dispatch(action))
  .run();

Can anyone suggest why you prefix voidthe map function so that it returns undefinedevery time?

+4
source share
3 answers

This is essentially a smart way of defining a function that returns undefined.

From MDN :

The void operator evaluates the given expression and returns undefined.

Your code essentially matches:

return someFunctionThatReturnsAnArray()
  .map((action) => { dispatch(action); })
  .run();

I will be honest: if I came across this code in any project that I work with, I would call it for review. This makes no sense and is potentially confusing.

+2
source
Operator

void , , , undefined, .

:

  • dispatch,
  • map undefined,
  • run Array (, ), , .

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();
0

https://eslint.org/docs/rules/no-void

void undefined: void undefined. , :

void - "" undefined ES5 undefined:

// 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 code minimization, since void 0 is shorter than undefined:

foo = void 0;
foo = undefined; 

When used with IIFE (direct function expression), void can be used to force

function keyword that should be considered as an expression instead of 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 styles of code prohibit the void operator, marking it as non-obvious and hard to read.

I see no reason to use it in the fragment provided.

0
source

Source: https://habr.com/ru/post/1696070/


All Articles