2

Given a function like the following, what is the correct syntax to use in order to be able to call showToast({ text: "some text"}) and still get the default values for params.autoHide and params.action ?

function showToast (params = {text: 'Something happened!', autoHide: false, action: 'CLOSE'}) {
    //noinspection JSUnresolvedFunction
    const toast = $mdToast.simple()
        .textContent(params.text)
        .position('top right')
    ;

    if (!params.autoHide) {
        toast.hideDelay(false);
    }
    if (params.action) {
        //noinspection JSValidateTypes
        toast.action(params.action); // label for close btn
    }

    $mdToast.show(toast);
}
yar1
  • 1,331
  • 2
  • 15
  • 26

2 Answers2

2

You can use object destructuring in the argument list too. The only thing that changes is you must not access the parameters through the params object:

function foo({text = "Hi", autoHide = false, action = "CLOSE"} = {}) {
  console.log(text + " " + autoHide + " " + action)
}

foo({text: "asd"});

See babel/repl.

Notice the = {} default value for the destructuring object. This makes it possible to call the function without a single parameter: foo();.

Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
1

You can use parameter object destructuring to achieve this:

function showToast({text = 'Something happened!', autoHide = false, action = 'CLOSE'} = {}) {
    //noinspection JSUnresolvedFunction
    const toast = $mdToast.simple().textContent(text).position('top right');

    if (!autoHide) {
        toast.hideDelay(false);
    }
    if (action) {
        //noinspection JSValidateTypes
        toast.action(action); // label for close btn
    }

    $mdToast.show(toast);
}

showToast({ text: "some text" }) // defaults autoHide to false, action to 'CLOSE'

See "Setting a function parameter's default value".

David Sherret
  • 101,669
  • 28
  • 188
  • 178