Renaming and Destructuring Variables in ES6

Image by Maxime VALCARCE.

One of my favourite features of modern JavaScript is destructuring and renaming nested data; especially as we work in a world where frontend developers are expected to know how to handle such data efficiently. This is especially common when you're working with APIs, or building anything more complex than very simple and straightforward static websites or apps.

It can be hard to write DRY (Don't Repeat Yourself) code when dealing with nested data, often running into situations where you end up writing very similar or repetitive code. Let's look at a quick example, using data from the Open Weather API which until very recently I used right here on my personal website to determine the current weather here in Brighton when a visitor came to the site (I now use a BBC feed):

const data = {  "coord": {    "lon": 50.82,    "lat": 0.1372  },  "weather": [    {      "id": 800,      "main": "Clear",      "description": "clear sky",      "icon": "01d"    }  ],  "base": "stations",  "main": {    "temp": 282.55,    "feels_like": 281.86,    "temp_min": 280.37,    "temp_max": 284.26,    "pressure": 1023,    "humidity": 100  }}

When presented with this data, you might extract the first current weather condition's main name and description using dot and bracket notation like this:

const main = data.weather[0].main;const description = data.weather[0].description;

That's all well and good. Up until a few years ago, that would have been moreorless the only way to do it, but it's not DRY. There's a lot of repetition in there (accessing data.weather[0] each time), takes longer to write, and that leads to code bloat with the risk that a relatively simple data change could break things. If we wanted to destructure this info and deal with it in a more efficient way, we could do it like this:

const { main, description } = data.weather[0];

This is called destructuring. With this code, we're accessing the weather property of the data object as before and then pulling out the main and description properties into toplevel variables which we can then access simply using main and description.


Renaming, Whilst Destructuring

This is great, but it does mean that the property names in our (possibly external) data are dictating the const or variable names within our code. What if you didn't want to use the names passed down via the data, or already had a main and/or description within your code? What if the names just aren't descriptive enough in the context of your component?

Here's where renaming whilst you're destructuring comes into play, here's the same example again, but now with renaming included:

const { main: weatherName, description: weatherDescription } = data.weather[0];

I'm sure that snippet is relatively selfexplanatory: we're still extracting main and description from data.weather[0], but now we rename them at the same time as weatherName and weatherDescription so that they fit better within your codebase and naming conventions. We do this by using a : immediately after the property you're destructuring, followed by the name you would like to use.


Nested Destructuring

There's one last piece of the puzzle for this article, and that's the fact that in our example, we are still selecting the first array item on the righthand side: data.weather[0]. We can destructure the first array item too by moving the weather array pattern over to the lefthand side like this:

const {  weather: [{ main: weatherName, description: weatherDescription }],} = data;

What's important to realise in this situation is that weather labels the source property and does not become a variable. We still only get weatherName and weatherDescription.

If you still want direct access to the first weather object as well, you can destructure the same source property separately:

const {  weather: [weather],  weather: [{ main: weatherName, description: weatherDescription }],} = data;

I'll admit, I'm not that keen on this particular aspect of destructuring, but from experience, the use case where you need to access a nested object, as well as elements within it separately is fairly rare.


Bonus: Destructuring Within a Method

Personally, probably the best part about destructuring in JavaScript is the fact that it can also be done inline, for example as part of a map.

Say we have this example data:

const cars = [  {    brand: 'Alfa Romeo',    model: 'Stelvio Quadrifoglio'  },  {    brand: 'Audi',    model: 'RS6'  },  {    brand: 'Volkswagen',    model: 'Polo'  },];

If we wanted to loop over these traditionally to output each brand followed by the model, it would look a little like this:

cars.map(car => (  <p>    {car.brand}: {car.model}  </p>));

However, you can cut that repetition and tidy things up using destructuring:

cars.map(({ brand, model }) => (  <p>    {brand}: {model}  </p>));

This is a fairly highlevel and rudimentary example just to illustrate the point, but this technique, even when combined with nested destructuring and renaming, leads to much simpler code, written much more quickly.

Ultimately, destructuring is now a very common part of a web developer's work and renaming whilst you are destructuring is an efficient and important part of keeping your code maintainable, clear and easy to read.


Want to find out more?

If you need senior handson support with a complex React or Next.js platform, migration, performance issue, or technical SEO problem, send me the context and I'll tell you where I can help.