Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 266
Yedhu Krishnan Avatar asked Jun 09 '26 08:06

Yedhu Krishnan


2 Answers

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"
like image 63
ZER0 Avatar answered Jun 10 '26 20:06

ZER0


const someFunc = ({a, b, c ,d} = {a:10, b: 12, c:3, d:4}) => {
   console.log(a, b, c ,d);
}
someFunc()

Remember that this code wont actually work in IE.

Here is the workaround for IE:

    var someFunc = function someFunc() {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
       a: 10
    },
    a = _ref.a;

    //here starts the function
    console.log(a);
};
someFunc();
like image 23
Ifaruki Avatar answered Jun 10 '26 20:06

Ifaruki