Daily Uses for Destructuring Assignment in Javascript
According to MDN, the definition of destructuring assignment is that it’s syntax in a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. This is an excellent tool to use in both pure javascript and in frameworks. Let’s checkout some ways we can implement destructuring into our code.
Event Listeners
One way that I was exposed to destructuring assignment was in a situation where you had an event listener listening for different properties on your frontend. For example, take coordinates.
Before Destructuring
const coords = (e) => {
let offsetX = e.offsetX
let offsetY = e.offsetY console.log(offsetX, offsetY)
}
window.addEventListener('mousemove', coords)After Destructuring
const coords = (e) => {
let { offsetX: x, offsetY: y } = e console.log(x, y)
}
window.addEventListener('mousemove', coords)
Typically, you’ll need to listen for both the offSet of x and the offSet of y to locate the coordinates of your cursor. Instead of having to bring up things like e.offsetX and e.offsetY whenever we want something for our event, we can simply destructure it into an object instead. This makes our code much easier to read and keeps our code nice and DRY (don’t repeat yourself!).
Passing State as Props (React)
While researching, I came upon an article by Niels Gerritsen that gave me a tip that I’ll definitely use in my react projects. This little tip helps you keep the clutter out of your JSX while passing state through as props to certain components.
Before Destructuring
return (
<div>
<h1>{props.name}</h1>
<img src={props.image.url} alt={props.image.title}/>
<h3>{props.content}</h3>
</div>
);After Destructuring
const {name, content, image} = props;
return (
<div>
<h1>{name}</h1>
<img src={image.url} alt={image.title}/>
<h3>{content}</h3>
</div>
);
Normally, we have our props that carry our state of things like name, image, and content. However, if you’ve done a bit of prop drilling before you know how sometimes your JSX can turn into a really abstracted bit of information. React Hooks help us take “this” out of the chain of abstraction, but destructuring assignment can help clean up our code, too!
When we save our variables as our props we’ve now pulled them out of their cages and can use them how we need. This way our code is way easier to read and it’s easy for the user to see which props we will use in our return.
Be sure to check out the docs I linked at the top of the blog to see all of the other things that destructuring can do!