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?
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"
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With