Default Parameter Values On Javascript Functions

ES2015 (aka ES6)

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:

[code]
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’);
[/code]

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:

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

myFunc(‘someValue’);
[/code]

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.

Privates In ES2015 Javascript Classes

One feature missing in ES2015 (formerly ES6) classes is the concept of a private variable or function. However, thanks to ES2015 modules we can …

TypeScript vs ECMAScript 2015/2016

As Javascript slowly becomes a less salty language thanks in part to ECMAScript 2015 (formerly ES6) amd ECMAScript 2016 (formerly ES7), the question …

Abstract Classes In Javascript

Modern Javascript is a lot different to Javascript of 2010. We have considerably more methods and means of doing things that we did not have …

A Guide To ES6 Classes

You might have noticed I have been writing about ES6 a lot lately. This is because I am excited about ES6 and thanks to the use of transpilers we can …