Interesting way to assign variables

I have a function that detects if two nodes (shapes) in an array are overlapping or not.

The way to tell that is interesting, but not the point of this post.

What’s interesting is that each node has to run through a function.

The function I’m using, called ‘areRectanglesOverlapping’ takes two arguments: rectangle1 and rectangle two:

function areRectanglesOverlapping(rectangle1, rectangle2, overlap = 3) {
//...
}

The third argument is one with a default value assignment of 3; it’s the tolerance level at which two rectangles can overlap.

In order to determine if two shapes are overlapping, I need each rectangle’s width, height, position, and rotate angle.

I realized that each rectangle has the same properties; i wanted to extract out the properties from the node object and assign to variables to use in the rest of the function. But since each rectangle has the same properties, I can’t use deconstruction to extract them out.

this won’t work:

const {width, height, rotateAngle, offsetX, offsetY} = rectangle1
const {width, height, rotateAngle, offsetX, offsetY} = rectangle2

So I asked ChatGBT about this issue.

It responded with something clever. Something I didn’t know we could do in JS.

const {
    offsetX: x1,
    offsetY: y1,
    width: width1,
    height: height1,
    rotateAngle: angle1,
  } = rectangle1
  const {
    offsetX: x2,
    offsetY: y2,
    width: width2,
    height: height2,
    rotateAngle: angle2,
  } = rectangle2

What we’re doing is deconstructing each parameter (rectangle1, rectangle2), extracting out their properties and assigning those properties to new variables.

So the rest of the function is using these variables:

x1, x2, y1, y2, width1, width2, angle1, angle2, height1, height2

That’s a very interesting way to use deconstruction to assign variables of two parameters that have the same properties.

Here’s the official documentation about Destructuring.

Destructuring assignment - JavaScript | MDN

Far down the page is the write up of this very thing I show above in the “Assigning to new variable names” section.


Fun times.