Skip to main content

Command Palette

Search for a command to run...

Is Destructuring the Cleanest Way to Handle Variables in JavaScript?

Ever found yourself tangled up in a bunch of variables? Me too!

Updated
5 min read
Is Destructuring the Cleanest Way to Handle Variables in JavaScript?
D
I’m a software engineer who loves creating strong and reliable systems that help ideas work smoothly behind the scenes. I enjoy solving real problems and building solutions that make technology simple and useful for everyone. Along the way, I share what I learn through blogs and tutorials to help others understand backend development better. My goal is to make the tech world easier to explore and more helpful for all. Let’s build, learn, and grow together.

Let me take you through a little story of how I, as a JavaScript developer, once found myself in a messy heap of variable assignments and how a nifty little feature called "Destructuring" saved the day.

Scene 1: The Traditional Way – A Tedious Start

It all began when I was working on a weather app. I had an API response with a whole bunch of data, and I needed to assign specific values to variables for later use.

Here’s what the traditional way of assigning variables looked like:

const weatherData = {
  temperature: 24,
  humidity: 80,
  windSpeed: 10,
  description: "Partly Cloudy",
};

const temp = weatherData.temperature;
const humidity = weatherData.humidity;
const windSpeed = weatherData.windSpeed;
const description = weatherData.description;

console.log(temp, humidity, windSpeed, description);

Now, you might think, "Hey, this looks okay." But imagine if the object had 10, 20, or even more properties. I found myself writing line after line of repetitive code, and the more variables I extracted, the more complex the code became. It wasn’t pretty.

The Problem?

Too much boilerplate! And let’s be honest, it’s not the most readable, right? The traditional approach can get cumbersome, especially when you’re dealing with larger objects or multiple objects at once. As a developer, this was slowing me down.

That’s when I asked myself: Is there a better way?

Scene 2: Enter Destructuring – A Breath of Fresh Air

One day, I stumbled across something called destructuring, a feature introduced in ES6 (ECMAScript 2015). At first, it sounded complicated, but the concept is simple—extract values from arrays or objects and assign them to variables in one go.

Take a look at how destructuring changed my life (and my code):

const { temperature, humidity, windSpeed, description } = weatherData;

console.log(temperature, humidity, windSpeed, description);

Boom! With a single line, I was able to extract the same values. No more repetitive assignments. No more clutter. It’s clean, elegant, and does exactly what I need without the fluff.

The Magic of Destructuring: How Does It Work?

Destructuring allows you to unpack properties from an object (or elements from an array) and assign them directly to variables.

Here’s a breakdown:

  • Object Destructuring: You specify the property names inside curly braces {} and assign them directly from the object. The variables will automatically be assigned the corresponding values from the object.
const { property1, property2 } = object;
  • Array Destructuring: You use square brackets [] to unpack values from an array into variables.
const [firstValue, secondValue] = array;

And just like that, you're avoiding repetitive code and making your script way more readable.

Scene 3: A Real-Life Scenario – Nested Destructuring

But wait—there’s more! I was soon tasked with handling an even more complex API response with nested objects. Destructuring came to the rescue once again, and this time, it got even cooler.

Here’s the traditional way:

const response = {
  location: {
    city: "San Francisco",
    country: "USA",
  },
  forecast: {
    temperature: 18,
    wind: {
      speed: 15,
      direction: "NW",
    },
  },
};

const city = response.location.city;
const country = response.location.country;
const windSpeed = response.forecast.wind.speed;

console.log(city, country, windSpeed);

And here’s how I handled it with nested destructuring:

const {
  location: { city, country },
  forecast: {
    wind: { speed: windSpeed },
  },
} = response;

console.log(city, country, windSpeed);

Cool, right? I extracted the properties from deeply nested objects in a clear and concise manner. Plus, the variable names I used like windSpeed are custom—no need to stick with the original property names.

Scene 4: Questions That Might Pop Up

Now, I know what you’re thinking. Let’s tackle a few common questions:

Q: Does destructuring work for arrays too?
Yes! Here’s an example:

const numbers = [10, 20, 30];
const [first, second, third] = numbers;
console.log(first, second, third);

Q: What happens if a property doesn’t exist?
By default, you’ll get undefined. But you can set default values:

const { temperature = 22, humidity = 60 } = weatherData;

Q: Can I skip elements while destructuring arrays?
Yes, you can skip by leaving commas without variables:

const [first, , third] = [10, 20, 30]; // Skips the second value
console.log(first, third);

Scene 5: Destructuring in Production – The Big Picture

Destructuring isn’t just a cool trick; it affects production in real, meaningful ways. Here’s why:

  • Improves Readability: Clean, concise code is easier to understand and maintain.

  • Reduces Boilerplate: Less repetitive code means fewer chances for bugs.

  • Makes Refactoring Easier: When you need to change variable names or extract more properties, it’s straightforward with destructuring.

  • Better Performance: While the performance difference is marginal, less boilerplate can make your application easier to optimize and debug.

Final Thought: When to Use Destructuring?

Destructuring is incredibly powerful when used wisely. For smaller objects or simple data, it’s a no-brainer. However, for very large, deeply nested objects, overusing destructuring could potentially hurt readability.

My rule of thumb? Use destructuring when it simplifies your code.

Destructuring transformed my approach to coding in JavaScript, making my code more concise and readable. So, next time you find yourself bogged down by assignments, ask yourself: Why not destructure?


Thank You!

Thank you for reading!
I hope you enjoyed this post. If you did, please share it with your network and stay tuned for more insights on software development. I'd love to connect with you on LinkedIn or have you follow my journey on HashNode for regular updates.

Happy Coding!
Darshit Anjaria