JavaScript defaults parameters

1 minute read

Function Defaults

Perhaps one of most “easy” way to broke something is to use function defaults workarounds This is first that come in mind when doing defaults in ES5:

function sum(x, y){
  x = x || 2; // if not defined use 2
  y = y || 3; // if not defined use 3
  return x + y;

sum(); // 5
sum(4, 5); // 9
sum(null, 4); // 6

But this does not work always as expected e.g. sum(0, 6); // 8. That’s because 0 is one of JS falsy values and || works as expected.

One way to fix this is to use more robust check:

function sum(x, y){
 x = (x != undefined ) ? x : 2;
 y = (y != undefined ) ? y : 3;
 return x + y;
sum ( 0, 4); // 4;
sum (undefined, 2); // 4

This means any value can be passed in even undefined. But undefined is specified as

undefined value primitive value used when a variable has not been assigned a value

But most important thing to remember in this case is that undefined is not JS reserved keyword but a property of Object with value undefined and attribute Writeble set to false.

So in short we do not say I am ommiting first parameter but rather I am setting the first parameter to value undefined which is not at all what we want to achieve with default values.

There is no way to omit left side parameters only to pass fewer than expected

ES6 diferences

In ES6 parameters of function default to undefined and there is no need to check explicitly for that

notes and updates: