Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does the anonymous JavaScript function f => f do?

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?

like image 654
SomethingOn Avatar asked Dec 20 '16 15:12

SomethingOn


People also ask

What does the => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

What do anonymous function do in JavaScript?

Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.

What is the purpose of anonymous function?

Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class. printf("Hello %s\r\n", $name);

What are two common uses of anonymous functions in JavaScript?

One common use for anonymous functions is as arguments to other functions. Another common use is as a closure, for which see also the Closures chapter. Use as an argument to other functions: setTimeout(function() { alert('hello'); }, 1000);


1 Answers

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.

like image 110
Felix Kling Avatar answered Oct 13 '22 00:10

Felix Kling