DEV Community

Discussion on: How Destructuring Works in JavaScript💢💢💢

Collapse
 
perrydbucs profile image
Perry Donham

One of the overlooked but incredibly useful ways to use destructuring is in the interface of a function. Think of a function with a signature such as:

const aFunc = function (size, weight, length, girth, width) { }

When writing client code that invokes this function, the developer has to either remember the correct order of the parameters or spend time looking it up.

With destructuring, we can write the function to take a single object as the input param:

const aFunc = function ( {size, weight, length, girth, width} ) { }

Now the dev simply writes the function call and passes an object with the appropriately named attributes:

const params = {
   size: 20,
   width: 30,
   length: 10,
   weight: 5,
   girth: 100
}

let result = aFunc(params)

The order of the named parameters now doesn't matter, since as long as the names are the same the function's parameters will be automatically populated. Combine this with default values for the input parameters and you significantly reduce the effort required to use the function.