We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

1man on 12/02/07


Tagged

javascript function arguments optional


Versions (?)


Who likes this?

5 people have marked this snippet as a favorite

luman
vali29
iTony
darkphotn
korzhik


Optional Function Arguments


Published in: JavaScript 


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".

  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 

You need to login to post a comment.