Created
September 13, 2012 13:49
-
-
Save miguelwicht/3714422 to your computer and use it in GitHub Desktop.
JavaScript function with optional arguments and default values
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
/* | |
* Exmaple for how to use a JavaScript function with optional arguments | |
* (1) define default values in object as key-value pairs | |
* (2) compare default_options with options and add default value if a | |
* key is not present in options | |
* (3) do what you want to do with your function | |
*/ | |
function doSomething(options) { | |
var default_options = { | |
'option1' : true, | |
'option2' : "Value2", | |
'option3' : "Value3", | |
'option4' : "Value4" | |
} | |
for(var key in default_options) { | |
if(typeof options[key] == "undefined") options[key] = default_options[key]; | |
} | |
// do stuff | |
} | |
doSomething({ | |
'option1' : false, | |
'option2' : "ValueX", | |
'option4' : "ValueY" | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment