šŸ“• Build AI Agents using LangGraph.js is now out!

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)

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

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