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.
It 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;
}
var state = arguments.length < 1 ? {} : arguments[0]
What's wrong with that? –
Farley undefined
. –
Alviani undefined
to a defaulting parameter, does the default still override it? That seems unintuitive. –
Farley undefined
is like passing nothing at all –
Terminator undefined
- the parameter will have the value undefined
. –
Alviani 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
.
© 2022 - 2024 — McMap. All rights reserved.