The Beginner’s Guide to JavaScript Default Parameters

In ES6, we can put the default values right in the signature of the functions.

Default parameters allow you to define a parameter in advance, which can be helpful in certain scenarios.

In ES5, we had to use the below approach.

        
function add(num1, num2) {
    return num1+num2;
}

add (2,3);    // Output : 5
add(5);       // Output : NaN as num2 is undefined        
    

In ES6, we had to use the below approach.

        
function add(num1=5, num2=10) {
    return num1+num2;
}

console.log (add (2,3));   // Output : 5
console.log (add (7));     // Output : 17 
console.log(add());        // Output : 15         
    

add (2,3) - When both argument are passed, num1 takes 2 & num2 takes 3.      

add(7)  - When one argument is passed, num1 takes 7 & num2 takes default value which is 10.

add( )  -  When no argument is passed, num1 & num2 takes default value which is 5 & 10 respectively.

Using Expressions as Default Values

It is also possible to provide expressions as default values.

Example 1: Passing Parameter as Default Values

        
function multy(x=2, y=x, z=x * y) {
    console.log(x * y *z);
}
 
multy();    // Output:16        
    

 Example 2: Passing Function Value as Default Value

        
const multy = () => 10;

const calculate= function(x,y=x * multy()){
    return x+y;
}

const result =calculate(10);
console.log(result);     // Output : 110        
    
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top