What does (state = {}) => state mean?
Asked Answered
H

3

10

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.

Hanoi answered 20/2, 2016 at 17:17 Comment(2)
possible duplicate of What's the meaning of “=>” (an arrow formed from equals & greater than) in JavaScript?Alviani
really not sure how this question got so many up-votesCommentative
S
9

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.

Sylvan answered 20/2, 2016 at 17:20 Comment(0)
T
8

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;
}
Terminator answered 20/2, 2016 at 17:34 Comment(9)
Default parameters don't replace falsy values.Repletion
Yes, now they should be equivalent.Repletion
That was weird, I didn't see this answer when I posted mine.Farley
var state = arguments.length < 1 ? {} : arguments[0] What's wrong with that?Farley
@PatrickRoberts: It doesn't work when you explicitly pass undefined.Alviani
@Alviani if you explicitly pass undefined to a defaulting parameter, does the default still override it? That seems unintuitive.Farley
@PatrickRoberts That's how it is, yes. passing undefined is like passing nothing at allTerminator
@PatrickRoberts: Yes it does. Passing no argument is the same as passing undefined - the parameter will have the value undefined.Alviani
@ruakh Thanks! I forgot to change the url... :)Terminator
M
3

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.

Money answered 20/2, 2016 at 21:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.