What exactly does the anonymous JavaScript function f => f do?
JavascriptLambdaEcmascript 6Javascript Problem Overview
I'm using a third-party library that has a function that takes functions as arguments. I'm doing some conditional checks to decide whether or not to add a particular function as a parameter and in some cases I don't want to provide a function. Providing null in that cases throws an error.
I found this code which works, but I don't fully understand what's happening.
compose(__DEV__ ? devTools() : f => f)
Is f => f
equivalent to () => {}
an empty anonymous function?
Javascript Solutions
Solution 1 - Javascript
f => f
is the identity function. It simply returns the argument that was passed in.
This function is often used as a default values for transformation processes, since it doesn't perform any transformation.
> Is f => f
equivalent to () => {}
an empty anonymous function?
No. The empty function doesn't return anything. The identity function returns the passed in argument.
Solution 2 - Javascript
f => f
is similar* to function(f){ return f; }
So close, but not quite what you expected.
* - as has been pointed out in comments, there are subtle differences, but for the sake of your question, I don't think they are particularly relevant. They are very relevant in other situations.
Solution 3 - Javascript
If you want to know what f => f
means, the left side is the parameter and the right side is the return value. So for example, f => f*2
, is equivalent to:
function(f) {
return f * 2;
}
The code which you describe returns whatever is supplied to it as input.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Solution 4 - Javascript
Others have already mentioned what f => f
does, so I'm not going to go deeper into that. I'm just going to explain the rest of the function, because there's a bit of a difference between f => f
and __DEV__ ? devTools() : f => f
The ternary operator checks if __DEV__
is a truthy value, and if so, it return function devTools()
. otherwise, it return the identity function f => f
which does nothing. Put differently: this code enables some development mode functions. Without the remaining code, it's hard to tell what this mode adds, but presumably, it will enable some extra logging information and less obfuscation.
Solution 5 - Javascript
Anytime with the similar dilemma, you can use Babel to get the answer.
It returned like this:
"use strict";
(function (f) {
return f;
});
BTW, => you used is ES6 feature called arrow expression. The other expression of interest
() => {}; // es6
would convert to:
(function () {});
Since arrow function expressions are always anonymous it makes sense if you add the name to the function:
let empty = () => {}; // es6
would convert to
var empty = function empty() {};