Optional Function Arguments


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

Simple way of allowing functions to take optional arguments. Always place the optional arguments last, so you don't have to explicitly pass an argument as "undefined".


Copy this code and paste it in your HTML
  1. function optionalArguments(a, /*optional*/b){
  2. if(!b){b = []};//If b isn't set, create an empty array
  3. //OR shorthand for this
  4. b = b || [];
  5. /*
  6. * The OR operator looks to see if b is true, if it is it skips
  7. * creating the Array. If b is false it creates the array. Not
  8. * very readable.
  9. */
  10. }

Report this snippet


Comments


You need to login to view comments.