Search code examples
javascriptobject-literalnamed-parametersdefault-parameters

How to set default values for named function parameters simulated via object literals in JavaScript?


I'd like to use named parameters (simulated via object literals) in my JavaScript functions for ease of readability. The code I've written works fine when I explicitly pass my parameters, but I'm having trouble trying to set a default value, so that my function can be called not only via as myFunction({someBoolean:true}) OR as myFunction() which would imply a default of someBoolean:false.

myFunction: function({myArgs}){
    myArgs.someBoolean = myArgs.someBoolean || false;
    if (myArgs.someBoolean) {
        [do stuff]
    }
    [do other stuff]
},

This works fine when I call myFunction({someBoolean:true}), but when I call myFunction(), I get "Uncaught TypeError: Cannot read property 'someBoolean' of undefined."

Thanks in advance!


Solution

  • Note the previous answer wouldn't work if you wanted multiple default arguments and some were provided:

    Doing myFunction({otherArg: 'hello'}) wouldn't necessarily set myArgs.someBoolean to false.

    Rather you should change it the below change:

    myFunction: function(myArgs){ // Switch to regular argument vs {myArgs}
        myArgs = myArgs || {}; // Make sure it provided
    
        myArgs.someBoolean = myArgs.someBoolean || false;
        myArgs.otherArg = myArgs.otherArg || 'defaultValue'
        if (myArgs.someBoolean) {
            [do stuff]
        }
        [do other stuff]
    },
    

    Then this could be called with: something.myFunction({someBoolean: true, otherArg: '...'})