最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to use a default value for named parameter in Javascript - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question edited Oct 16, 2024 at 5:15 Penny Liu 17.4k5 gold badges86 silver badges108 bronze badges asked Apr 20, 2020 at 11:12 Yedhu KrishnanYedhu Krishnan 1,24515 silver badges32 bronze badges 1
  • Does this answer your question? Set the default value for the object in javascript – yqlim Commented Apr 20, 2020 at 11:15
Add a comment  | 

4 Answers 4

Reset to default 13

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();

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({});

发布评论

评论列表(0)

  1. 暂无评论