Features of ES6 Part 3: Default Parameter Values

Wednesday, August 13, 2014

If a JavaScript function takes two parameters, we have always had the ability to invoke the function and pass two parameters, or one parameter, or no parameters, or three parameters if we wanted. In cases where we do not pass enough parameters, the author of a function might want to specify a default value instead of working with undefined.

Before ES6, developers applied default values to simple parameters using || expressions inside the function.

let doWork = function(name) {
    name = name || "Scott";
    return name;
};

With ES6, default parameters are explicit and appear in the argument list for a function.

let doWork = function(name = "Scott") {
    return name;
};

expect(doWork()).toBe("Scott");

A function can even calculate a default using something more than just a literal expression.

let doWork = function(x = Math.random()) { return x; }

The Significance of default parameters

The default parameter syntax is a good example of how ES6 is providing a clean syntax for a common requirement. No longer will we have to scan through a function implementation or documentation to discover the defaults.

Of course, not all parameters are simple values. A common programming technique for operations involving complex configurations, like an HTTP call, is to accept a single object argument and use some sort of extend API to merge the incoming configuration with configuration defaults (jQuery.extend or angular.extend, as two examples). Default parameters are useful in this scenario, too, but we’ll have to learn about object destructuring in an upcoming post, first.

Want more? Watch JavaScript Fundamentals for ES6 on Pluralsight!


Comments
gravatar Paweł Niedbała Thursday, August 14, 2014
It's just a detail but first code listing ("Before ES6...") shoud rather start "var doWork" instead of "let doWork" if it's really before ES6 :)
gravatar scott Thursday, August 14, 2014
Good point!
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!