šŸ“™ Understanding Neuronal Networks presale is now open - 20% off discount!

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)

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!


Leave a Reply

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