Hi Chromium devs,
If you don't read/review/author JS code in Chromium you can stop reading now.
Example
Before
function foo(opt_a) {
let a = opt_a || 'default_value';
console.log(a);
}
After
function foo(a = 'default value') {
console.log(a);
}
Notable difference
ES6 default parameter is
triggered ONLY if the parameter is passed as undefined. Passing null, or any other false-y value will not trigger the default parameter. This is explained better
here.
In other words, the ES5 equivalent of how ES6 default parameters work, is
function foo(opt_a) {
let a = opt_a === undefined ? 'default_value' : opt_a;
console.log(a);
which results in
foo(); // prints 'default_value'
foo(undefined); // prints 'default_value'
foo(0); // prints 0
foo(''); // prints ''
foo(null); // prints null
foo('bar'); // prints 'bar'
But in most cases where default parameters are implemented in existing code, the pattern shown in the 1st example of this email is used, which is lenient with false-y values, and therefore it would return
foo(); // prints 'default_value'
foo(undefined); // prints 'default_value'
foo(0); // prints 'default_value'
foo(''); // prints 'default_value'
foo(null); // prints 'default_value'
foo('bar'); // prints 'bar'
See
this example CL where migrating to ES6 default parameters, required changing "null" to "undefined" in functions that expect multiple optional parameters, as a way to trigger the ES6 default parameter.
Benefit
More concise code, and consistent default parameter behavior. Currently each author re-implements default parameters in each function, with slightly different behavior. This is also error prone. Consider the following example:
/** @param {number=} opt_a */
function foo(opt_a) {
let a = opt_a || -1;
console.log(a);
}
// Unclear if this is a bug or intended. Should zero be overriden,
// or was it an oversight about how false-y values work?
foo(0); // prints -1
Compatibility:
Looks good, except for iOS9 which does not seem to support it. We would need to restrict usage from any code that uses iOS9 (potentially with a PRESUBMIT warning, similar to what we've done with other ES6 features).
Interested hearing your thoughts.
Thank you,
Demetrios