1
{
  getter: {
    myThing: state => lookup => {
      return state.things[lookup];
    },
    myThings: state => {
      return state.things;
    }
  }
}

Given the above 2 functions, are the following equivalent?

{
  getter: {
    myThing: (state, lookup) => {
      return state.things[lookup];
    },
    myThings: (state) => {
      return state.things;
    }
  }
}
Justin808
  • 20,859
  • 46
  • 160
  • 265

1 Answers1

2

(state) => {} and state => {} are equivalent, since parentheses are optional around single arguments in arrow functions.

state => lookup => {} and (state, lookup) => {} are not equivalent.

The first expression is a function that takes one argument and returns another function that also takes one argument, whereas the second expression is a function that takes two arguments.

An expression such as a => b => {return a + b;} is an example of currying. You can use both variants like this:

const add = a => b => (a + b);
add(2)(3); // 5
add(2); // function add/<() // This refers to the `b => (a + b)` part
add(2, 3); // function add/<() // Like above, because the second argument is ignored

const add2 = (a, b) => (a + b);
add2(2)(3); // TypeError: add2(...) is not a function
add2(2); // NaN // b isn’t provided
add2(2, 3); // 5

(state) => (lookup) => {} would be equivalent to the first expression.


NB: (state) => (lookup) => {} requires an explicit return to return the value; omitting the curly brackets {} doesn’t.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • maybe you add that curly brackets require an expicit return statement for returning a value, different from `undefined`. – Nina Scholz Sep 22 '17 at 06:39