I will never use || (OR) for default values
TL;DR;
I will never use ||
for default values, but default parameter.
For example, instead of
function sort(array, startIndex, endIndex) {
startIndex = startIndex || 0;
endIndex = endIndex || array.length — 1;
...
}
I would use,
function sort(array, startIndex = 0, endIndex = array.length - 1) {
...
}
Why?
I have been using ||
for default values, till date.
But it bite me big time. A quick sort implementation in JavaScript,
fell in to infinite recursion
,
because of ||
, when an already sorted array was passed.
Long story short, w.r.t the above quick sort implementation in JavaScript
even if endIndex
will be passed as 0
(zero), on purpose, it would be evaluated to array.length - 1
.
As 0
is a falsy
value in JavaScript. Same would happen if ''
or null
, is passed as endIndex
,
or any other falsy
values.
However the intention have been, if endIndex
was not passed (undefined
), then evaluate it to array.length — 1
.
Thus, modifying the condition to
endIndex = endIndex === undefined ? length - 1 : endIndex;
, resolves the issue.
ES2015 nakes it easier with default parameter.
With default parameters, the
undefined
checks in the function body is no longer necessary.
So, instead of
function sort(array, startIndex, endIndex) {
startIndex = startIndex === undefined ? 0 : startIndex;
endIndex = endIndex === undefined ? array.length — 1 : endIndex;
...
}
I would use,
function sort(array, startIndex = 0, endIndex = array.length - 1) {
...
}
If you have enjoyed reading this post you can follow me on twitter @sarbbottam and learn about any new posts. Opinions expressed are solely my own and do not express the views or opinions of my employer.