šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Array destructuring in Javascript with renaming

The JS chained object-array destructuring is quite a powerful feature that can make the code shorter, and more concise.

For example, I had a situation where I was receiving a set of results with the following structure:

rectangle = {
    // where the rectangle starts and how tall and wide it is
    coordinates: [10, 20, 100, 100],

    // metadata the rectangle
    color: 'red', 
    label: 'first object',
    price: 120
}

And had a function that was drawing the rectangle:

const drawObject = (x, y, width, height, color, label, price)

A default call to drawObject() with an rectangle object type can be quite verbose:

drawObject(
    rectangle.coordinates[0], 
    rectangle.coordinates[1],
    rectangle.coordinates[2],
    rectangle.coordinates[3],
    rectangle.color, 
    rectangle.label, 
    rectangle.price
)

Realized that I could change this long declaration by taking advantage of the Javascript destructoring and the fact I can assign names to each element in the coordinates array:

/* first destructure the inital rectangle object  in:
- coordinates, 
- color, 
- label 
- and price
{coordinates, color, label, price}
and then destructure the coordinates array and rename each element:
[x, y, width, height] */
const drawObject = ({[x, y, width, height], color, label, price})

And now we can have a much cleaner call with just one parameter:

drawObject(rectangle)

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *