Optional arguments for Javascript functions

Javascript doesn’t allow you to define default values for function arguments. But sometimes you want some arguments to be optional. This is how you can do it:

function myConnect(host, port){
 // default to port 80 if nothing is set
 var port = (typeof port === 'undefined') ? 80 : port;
 return host + ':' + port;

Call myConnect(‘some.host’) most of the times and for those rare cases you need to connect to another port than 80: myConnect(‘special.host’, 1725)

1 comment

  1. Nice tip. I’ve been doing this for a while:

    var port = port || 80;

    Which looks nicer but has one downside: it won’t work correctly if the optional parameter is passed with a value of zero, so it must be used with caution. A possible use case is when the variable is assumed to be an object, so we would do something like:

    var object = object || {};

    This can also be useful in other situations, for example if we use an object variable as a namespace and another Javascript file could have initialized it before.