Wikipedia

Search results

31 January 2015

Optional Javascript Function Parameters

Optional parameters can be included in Javascript functions without the need to specify a default value. Some view this as a bug in Javascript that can miss errors, while others view it as a flexibility similar to what can be observed in life.

>>> def xyz (a, b, c=None):
...   print (a)
...   print (b)
...   if (c):
...     print (c)
... 
>>> xyz(1,2,3)
1
2
3
>>> xyz(1,2)
1
2


Without specifying a default 'None' value, the function would throw an exception if there is arity mismatch, as would be in C, ML, and just about every other strong or static procedural or functional language. In Javascript, however, the parameter's use is only bound to their reliance within the function. It would be

> function xyz (a, b, c) {
... console.log(a)
... console.log(b)
... if (c) { console.log(c) }
... }
> xyz(1,2,3)
1
2
3
> xyz(1,2)
1
2