I was building an App in react where I found a line in one of the boiler plate projects.
(state = {}) => state
Can anyone explain to me what the above line means? It's JavaScript ES6 standard.
I was building an App in react where I found a line in one of the boiler plate projects.
(state = {}) => state
Can anyone explain to me what the above line means? It's JavaScript ES6 standard.
Share Improve this question edited May 14, 2023 at 13:40 dumbass 27.2k4 gold badges36 silver badges73 bronze badges asked Feb 20, 2016 at 17:17 Shivanand MitakariShivanand Mitakari 5154 silver badges11 bronze badges 2- 2 possible duplicate of What's the meaning of “=>” (an arrow formed from equals & greater than) in JavaScript? – Bergi Commented Feb 20, 2016 at 18:08
- really not sure how this question got so many up-votes – Mulan Commented Feb 21, 2016 at 8:49
3 Answers
Reset to default 9It is a(n arrow) function that returns its input. If the input is not defined it will become the default value {}.
You might have seen it in combination with using redux' "connect", as the function that maps the store's state to the projection used for the connected component. If there is no state available, the empty object will be provided.
That's an arrow function with a default parameter that returns its input or an empty object, if no input was provided. It is similar to this es-5 function:
function(){
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
return state;
}
You might be more familiar with this notation:
function(state) {
if (!state) state = {}; // state defaults to {}
return state;
}
What you saw is ES6 syntactic sugar: function(state = {}) { ... }
is a shorthand notation for default values (state
defaults to {}
), and (a) => b
is a shorthand notation for function(a) { return b }
. If you put them together, you get (state = {}) => state
.