Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

= {}

could mean the default value of the function parameter, but what's the usage for the code inside previous braces?

like image 978
Man Shen Avatar asked Feb 23 '17 14:02

Man Shen


2 Answers

This is ES2015 syntax. Your function declaration combines a Destructuring assignment with a default value.

This is a basic destructuring assignment 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 hand side:

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

When you name arguments when declaring a function, you don't use var, and with object destructuring 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 doesn't have to take any arguments.

function test({a = "foo", b = "bar"} = {}){
    console.log(a + b);
}
test(); // "foobar"
like image 185
Aurel Bílý Avatar answered Sep 18 '22 01:09

Aurel Bílý


It's simply the way of doing default parameters using destructuring. You need the last bit as you suggested as a default.

Consider the following, which like the example uses a destructuring assignment:

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

let something = 1;
withDefault();

versus this one, which is missing the default, and which throws 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.
like image 42
msanford Avatar answered Sep 17 '22 01:09

msanford