Template for a Javascript function with optional and mandatory arguments passed as an object collection


/ Published in: JavaScript
Save to your folder(s)

A simple template for a JavaScript function which allows for an arbitrary number of named arguments to be passed in. This is achieved by passing a single object as an argument with each of the 'real' arguments being a key/value pair. In this way arguments can be passed in any order and we can easily add in new arguments.

To call, simply pass in an object with the required arguments:
myFunction ({opt1: 'cat', opt4: 'dog', opt2: 'monkey'})

Validates clean in jsLint.


Copy this code and paste it in your HTML
  1. function myFunction(options) {
  2. // options may contain: opt1, opt2, opt3, opt4
  3.  
  4. 'use strict';
  5.  
  6. // Where a mandatory parameter is missing, throw an error
  7. if (typeof options !== 'object' || options.opt1 === undefined || options.opt2 === undefined) {
  8. throw {name: 'Error', message: 'Missing options property: opt1 and opt2 must be provided'};
  9. }
  10.  
  11. // Where an optional parameter is missing, set it to the default value
  12. var key,
  13. default_options = {
  14. opt3 : 'dog',
  15. opt4 : 99
  16. };
  17.  
  18. for (key in default_options) {
  19. if (default_options.hasOwnProperty(key)) {
  20. if (options[key] === undefined) {
  21. options[key] = default_options[key];
  22. }
  23. }
  24. }
  25.  
  26. // All arguments are now available in the format options.opt1, options.opt2, etc
  27.  
  28. // Rest of function...
  29.  
  30. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.