Javascript - Operator Destructured Parameters

Introduction

The destructuring syntax can be used while passing function parameters.

The following code shows how to destruct array parameters:

function sum( [ num1, num2 = 0 ] ) { 
    console.log( num1 + num2 ); 
} 

sum( [ 1, 2 ] );         // 3 
sum( [ 1 ] );            // 1 
sum( [  ] );             // NaN 

Here, the sum() function when passed in an array of two values 1 and 2 prints their sum 3.

When passed only one value 1, it outputs 1 due to the fact that num2 has a default value of 0 assigned.

When no value is passed to the destructured array, it prints NaN (Not a Number) because even though num2 defaults to 0, num1 is set to undefined.

Destructuring can help to better read and fetch the required properties of options needed inside the function.

We can create a function definition using destructured parameters as follows:

function createObj(name, value, {x:a, y:b, z:c}) { 
    // code to return object 
} 

The third argument uses destructuring to fetch the corresponding values object.

It is easy to understand what inputs are required by the function by looking at the function definition.

Destructured parameters act like regular parameters in the sense that they are set to undefined if not passed.

Related Topic