Optional function arguments/parameters by using associative array


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

By not being limited to provide certain arguments/parameters in right order when calling a function, makes the function more versatile and easier to extend without breaking old code (e.g. calls to the function).
One solution is to pass an associative array holding the parameters.
Advantage: argument order is unnecessary, each argument have a label - easier to remember.


Copy this code and paste it in your HTML
  1. function someFunction(params) {
  2. var a = (params.a === undefined) ? "default value" : params.a /* If undefined, set default value */,
  3. b = (params.b === undefined) ? "default value" : params.b /* If undefined, set default value */,
  4. sum = a + b,
  5. myobject = {},
  6. i,
  7. j,
  8. el = (params.el === undefined) ? document.getElementById("default") : params.el /* If undefined, set default value */,
  9. style = el.style;
  10. // do something with el and style...
  11.  
  12. // function body...
  13. }
  14.  
  15. // call function with associative array:
  16. someFunction({
  17. a: 'Dette er en titel',
  18. b: 'http://www.dr.dk/OmDR/Nyt_fra_DR/Nyt_fra_DR/2008/11/25141639.htm',
  19. el: document.getElementById("result")
  20. })

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.