Skip to content

Instantly share code, notes, and snippets.

@miguelwicht
Created September 13, 2012 13:49
Show Gist options
  • Save miguelwicht/3714422 to your computer and use it in GitHub Desktop.
Save miguelwicht/3714422 to your computer and use it in GitHub Desktop.
JavaScript function with optional arguments and default values
/*
* 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