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 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?
- Does this answer your question? Set the default value for the object in javascript – yqlim Commented Apr 20, 2020 at 11:15
4 Answers
Reset to default 13I 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();
ES6 accepts default values for parameters :
const someFunc = ({a} = {a : 6}) => {
console.log({a})
}
someFunc({ a : 3 })
someFunc()
const someFunc = ({ a }) => {
typeof a === 'undefined'
? a = 'some default'
: a = a;
console.log(a);
}
a = 'some value';
someFunc({ a });
someFunc({});