JS function declaration: curly brace object assigned as an empty object in parameter declaration

Here is the code

export function createConnect({ connectHOC = connectAdvanced, mapStateToPropsFactories = defaultMapStateToPropsFactories, mapDispatchToPropsFactories = defaultMapDispatchToPropsFactories, mergePropsFactories = defaultMergePropsFactories, selectorFactory = defaultSelectorFactory } = {}) {...} 

What does {connectHOC = connectAdvanced ...} = {} mean inside the function parameter declaration?

I know that

 = {} 

may mean the default value of the function parameter, but what is the use of the code in the previous curly braces?

+6
source share
2 answers

This is the syntax of ES2015. A function declaration combines Destination Assignment with a default value.

This is the basic purpose of destructuring using an object:

 var {a, b} = {a: "foo", b: "bar"}; console.log(a); // "foo" console.log(b); // "bar" 

You can add default values ​​to the left side:

 var {a = "foo", b = "bar"} = {}; console.log(a); // "foo" console.log(b); // "bar" 

When you specify arguments when declaring a function, you do not use var , and when you destroy the object, it will be the same:

 function test({a = "foo", b = "bar"}){ console.log(a + b); } test({}); // "foobar" test({b: "boo"}); // "fooboo" 

And of course, you can define a default value so that your function does not accept any arguments.

 function test({a = "foo", b = "bar"} = {}){ console.log(a + b); } test(); // "foobar" 
+5
source

This is just a way to execute default parameters using destructuring. You need the last bit, as you suggested by default.

Consider the following, which, as in the example, uses the destruction destination :

 function withDefault({parameter=something} = {}) { console.log(parameter) } let something = 1; withDefault(); 

compared to this, which has no default value and which causes an error:

 function withoutDefault({parameter=something}) { console.log(parameter) } let something = 1; withoutDefault(); // It needs to be called as withoutDefault({}), withoutDefault(1) or // with some value, since the function signature doesn't define a default // in this case. 
+3
source

Source: https://habr.com/ru/post/1015219/


All Articles