javascriptnamed-parametersdefault-parameters

How to use a default value for named parameter in Javascript


I have a javascript function that takes an object as a parameter like this:

const someFunc = ({ a }) => { <do something> }

I call the function like this:

a = 'some value'
someFunc({ a })

But sometimes, I need to call the function without passing a. In that case, I need to use a default value for a. How can I add a default value for a key inside an object?


Solution

  • I think you're looking for default parameters

    const someFunc = ({ a = "foo" }) => {
       console.log(a);
    }
    someFunc({}); // "foo"
    someFunc({a: "bar"}); // "bar"

    Update If you also want to have a as default to "foo" without passing any argument, you need to set a default parameter also for the object that contains a. Something like:

    const someFunc = ({ a = "foo" } = {}) => {
       console.log(a);
    }
    someFunc(); // "foo"