I want to better understand es6 arrow functions.
Given the following example:
export default function applyMiddleware(...middlewares) { return (createStore) => (reducer, preloadedState, enhancer) => { // snip actual enhancer logic return { ...store, dispatch } } }
Describing the above in words:
So without the arrows it would look like this:
export default function applyMiddleware(...middlewares) { return function(createStore){ return function(reducer,preloadedState,enhancer){ //some logic return{...store,dispatch} } } }
My questions:
An easy way to grasp this is to remember that a curried/double arrow function is a function that implicitly returns another function(s). Going by this logic, you could also have triple arrow functions and so on.
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.
An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.
Arrow functions are anonymous functions (the functions without a name and not bound with an identifier). They don't return any value and can declare without the function keyword. Arrow functions cannot be used as the constructors. The context within the arrow functions is lexically or statically defined.
The answer to your first question is more or less (see my comment). The answer to your second question is that the pattern you are seeing is a combination of using a closure and currying. The original parameters to the exported function get gathered into an array called 'middlewares' that the returned functions close over (i.e. have access to). The function then can be called again with yet another parameter 'createStore' then another function is returned that can accept even more parameters. This allows one to partially apply the parameters. For a more trivial (and perhaps more easily comprehended) example, lets take a function called 'add' that adds two numbers:
let add = (x, y) => x + y;
Not very interesting. But lets break it up so it can take the first number and return a function that takes the second:
let add = x => y => x + y; let add3 = add(3); let seven = add3(4); // 7
This may not seem like a big win for our add function, but you started with a much more reasonable real-world example. Additionally, rather than currying manually it is possible (and desirable) to use a curry function that does it for you, many popular libraries (lodash, underscore, ramda) implement curry for you. An example using Ramda:
let add = R.curry((x, y) => x + y); let add3 = add(3); let five = add3(2); let also5 = add(3, 2); let still5 = add(3)(2); // all are equivalent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With