Last active
January 17, 2019 16:32
-
-
Save johannes-jansson/bc36fa291f8c9d1a14b69a0dadde8e57 to your computer and use it in GitHub Desktop.
JS function with optional parameter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is our method for doing optional parameters in javascript. | |
// In this example source is a mandatory parameter, opts are optional, | |
// and callback is an optional callback. Optional parameters are stored | |
// in the object opts. | |
const myfunction = (source, opts, callback) => { | |
// check if any optional parameters were provided by looking at the type of the second argument | |
if (typeof opts === 'function') { | |
// If opts is a function it's the callback | |
callback = opts; | |
// Set opts to be an empty object | |
opts = {}; | |
} | |
// Then create consts for all parameters, containing | |
// either the value in opts, or the default value. | |
// So this is where you providde default values. | |
const params = opts && opts.params ? opts.params : {}; | |
const options = opts && opts.options ? opts.options : {}; | |
const commitHash = opts && opts.commitHash ? opts.commitHash : 'master'; | |
// do stuff | |
if (callback) callback(null); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment