Javascript - Destructured Parameters vs Default Parameters

Introduction

Using Object Destructured parameters allows us to have optional parameters in any position of the list of parameters.

function printNums( { num1, num2 } ) { 
    console.log( num1, num2 ); 
} 

printNums( { num2: 1, num1: 2 } );           // 2 1 
printNums( { num2: 42 } );                   // undefined 42 

Here, the printNums() function prints two numbers passed into a destructured object as parameter having properties num1 and num2.

In the first function call you can switch the order of the parameters by specifying num2 first and then num1.

By specifying only num2, you can actually set the value of the first intended parameter num1 as undefined.

There is difference in behavior between a destructuring default value and a function parameter default value. Consider this example:

function foo({ num1 = 42 } = {}, { num2 } = { num2: 42 }) { 
    console.log( num1, num2 ); 
} 
foo();               // 42 42 
foo( {}, {} );       // 42 undefined 

In the above example, the function foo takes two parameters:

  • { num1 = 42 } = {}
  • { num2 } = { num2: 42 }

When no argument is passed to the function, the first parameter defaults to an empty object {}.

But since it uses object destructuring, the named parameter num1 defaults to 42.

In the case of the second argument, the default parameter value is an object { num2: 42 }.

The parameter defaults to this object when there is no second argument provided to the function.

Related Topic