ES6 Default Parameter Expressions
/ 2 min read
I’ve read about something that I wouldn’t probably think about on a normal day: default parameter expressions in ES6 functions.
In ES5 version, we would probably use the following pattern to create a function with default parameter values:
function add(first, second) { first = first || 1; second = second || 2; // do things}
However, this has its pitfalls. For example, if one of the arguments is 0, then the function would take an OR
value, because 0 is falsey
. So you’d need to work with typeof
. So it would look like that
function add(first, second) { first = (typeof first !== "undefined") ? first : 1; second = (typeof second !== "undefined") ? second : 2; // do things}
However, today with ES6 we can simply do this
function add(first = 1, second = 2) { // do things}
The interesting discovery that I made for myself was that parameters can reference the previous ones, as in
function add(first = 1, second = first) { // do things}
Not the other way round though, because parameters are being created in sequence. So if we’re trying to reference the value of a second parameter, we can’t, because it hasn’t been created yet. Just like we wouldn’t with our let
and const
.
// Okaylet first = 1;let second = first;
// Not okayconst first = second;const second = 2;