Default Parameter Values On Javascript Functions

Last updated: February 6, 2015

It’s time for another ES6 post. This time, we’re talking about arguably one of the best additions to Javascript that is up there with modules and classes. I am talking about the ability to specify default parameter values on a Javascript function.

This is one of the biggest missing pieces in Javascript in my opinion. I have encountered the need for this numerous times and while you can definitely implement a solution that does the job, there has been no support for native parameter values until ES6.

Previously we had to implement default values using the typeof operator like this for ES5 capable browsers:

function myFunc(param1, param2, param3) {
    // param2 and param3 are optional parameters
    // If we don't have a param value, we set a default value which is currently an empty string ''
    param2 = (typeof param2 !== 'undefined') ? param2 : '';
    param3 = (typeof param3 !== 'undefined') ? param3 : '';
}

myFunc(‘someValue’);

While this approach definitely works and has served us well for a long time, we finally have native support for default parameter values on functions in ES6.

If you have used any other language like Java or PHP, then the default parameter values in Javascript’s ES6 specification will look familiar to you.

Default parameter values the ES6 way:

function myFunc(param1, param2='', param3='') {
    // param2 and param3 are optional parameters
    console.log(param1, param2, param3);
}

myFunc(‘someValue’);

Browser support for default parameter values

Unfortunately browser support is fairly nonexistent for default values. Even with ES6 features turned on in Chrome, they’re not supported. Firefox seems to fare pretty well for ES6 support and if you paste the above code into the Firefox console, it will run. In-fact, Firefox is currently the only browser that supports default parameter values.

You can keep track of browser support on the Mozilla documentation page for default parameter values here. In the mean time, you can still use them, just remember to use a transpiler like 6to5 or Traceur if you do.

 

Dwayne

 

Leave a Reply

Your email address will not be published. Required fields are marked *