Destructuring Assignment

Jacob Kenny
2 min readDec 28, 2020

As I was working on a new project my thoughts drifted back towards my first forays into the framework, and I remember being baffled by the frequent use of destructuring assignment (DA) that I saw. I was hesitant to begin using the technique myself, but DRY is king, and I eventually found that even though I felt awkward at first, I now find it to be a necessity.

For me, I utilize DA the most when dealing with a component’s props, and its state.

Above, I’ve included two possible implementations of the same component, one that utilizes DA, and the other doesn’t. I only realized after that the difference in this case wasn’t as stark as I thought, but at the same time, I think that anyone would agree that the second espouses the principals of DRY more effectively than the first. Rather than having to retype “props.” for each line, the second implementation uses DA on line two. Although it’s not fully apparent in this simple example, another added bonus is that using DA makes the JSX easier to read, and reduces the amount of JavaScript code that has to be written in the return statement.

Sometimes, as I write about a concept that I initially found interesting, I realize that maybe, just maybe, it’s not quite as interesting as I thought. DA may be one of those cases, but there is one final interesting case to be made for DA. Swapping variables is a common enough practice that nearly everyone can do in one way or another, often using a temporary variable to store the value of one of the variables. However, by utilizing DA on an array, we can actually swap variables without having to declare a temporary variable.

let x = 7, y = 10
[x,y] = [y,x]

Using this technique may obfuscate the code a little bit, but to me, that’s a small price to pay for being able to swap variables without needing to declare a third temporary variable.