Javascript - Function Default Parameters

Introduction

Functions in JavaScript allow you to call a function by passing any number of parameters irrespective of the parameters declared.

You can use any value for the parameters in case no argument is specified.

In Javascript 5, if the argument is not specified, its value would be set to undefined.

The pattern used to set defaults for unspecified parameters was something like this,

function sum(a,b) { 
    a = (a !== undefined) ? a : 1; 
    b = (b !== undefined) ? b : 41; 

    console.log( a + b ); 
} 

sum();            // 42 
sum(1, 2);        // 3 
sum(10);          // 51 
sum(null, 6);     // 6 

ES6 can set a default value to the parameter in the function declaration statement itself.

var sum2 = function(a = 1, b = 41) { 
   console.log(a + b); 
} 

sum2();            // 42 
sum2(1, 2);        // 3 
sum2(10);          // 51 
sum2(null, 6);     // 6 

Here, if we do not specify any argument, the default value of the parameter gets used.

Related Topics

Quiz