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:
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
However, today with ES6 we can simply do this
The interesting discovery that I made for myself was that parameters can reference the previous ones, as in
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
.