Demystifying the Destructuring in JavaScript!!

Demystifying the Destructuring in JavaScript!!

Know in depth, how the De-structuring works for Objects in JavaScript

This is a particular concept in JavaScript which has so many variations, some may seem daunting at first and some look like an obvious approach, given the solution.

Knowing in-depth about Destructuring of Objects in JavaScript comes in handy when you are dealing with writing code for complex applications, refactoring your code or making it simple to read.
This technique can save you so many lines of code and can make your code clean and organized, easy to debug and modify.

It is one of those concepts in JavaScript which is simple and complex at the same time, depending on your behind-the-code understanding and the practice hours you've put in with different variations of destructuring problems.
So, let's learn about it in the simplest way possible!!


What is Destructuring?

Destructuring — as the name suggests we're breaking the structure of a particular data structure or an object.
Now the question arises, why do we need it? And the answer is simple:

  • It allows us to unpack / extract values from arrays or objects and assign them to variables concisely and efficiently.

  • It is a shorthand syntax for assigning values to variables while extracting none or some of the features or data from an array or object.

Destructuring of Arrays:

Let's Understand the Destructuring for an Array with simple code snippets:

In array destructuring, you can assign the values of an array to individual variables. Here is how

const [a, b, c] = [1, 2, 3];
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

If we are already having an array and we want to extract first few variables from it, we can do it easily this way

const nums = [7,6,5,4];
const [x, y] = nums;
console.log(x, y); // 7 6

Destructuring of Objects:

Destructuring of Objects with simple code snippets:

In object destructuring, you can extract values from an object and assign them to variables with the same name as the object properties. For example:

const person = {
  name: 'Peter Parker',
  age: 30,
  gender: 'male'
};

const { name, age, gender } = person;
console.log(name); // 'Peter Parker'
console.log(age); // 30
console.log(gender); // 'male'

In the above example we've taken the variable names same as the name of keys in the person object, but this might not be the case everytime and there will be conditions where you want to rename the variables in which you're extracting the properties. This is how you can do that ↓

const person = {
  name: 'Peter Parker',
  age: 30,
  gender: 'male'
};
const { name : newName, age : newAge, gender : newGender} = person;
console.log(newName); // 'Peter Parker'
console.log(newAge); // 30
console.log(newGender); // 'male'

// Now that you've renamed the variables, using their original names will throw a Reference Error: name is not defined

The syntax is simple, the original property name followed by a colon ':', followed by the new name with which you want to rename the variable.


Miscellaneous Example:

Let's consider an example to make our understanding of object destructuring more robust — You are given an object and you need to extract only some of the properties out of it by 1.) using an arrow function 2.) using an Immediately Invoked Function

    1. We need to create an arrow function which is taking an object as an argument and extracting the required features from it right at the time of calling and then returns the object with only the desired (key: value) pairs.
const person = {
  name: 'Peter Parker',
  age: 30,
  gender: 'male'
};
//let's say we want an object with only name and gender of a person
const getNameGender = ({name, gender}) => ({name, gender});
console.log(getNameGender(person)); //{name: 'Peter Parker', gender: 'male'}
    1. Using an Immediately Invoked Function, immediately after declaring a function, we're going to call it with the object as an argument.
const person = {
  name: 'Peter Parker',
  age: 30,
  gender: 'male'
};
//the approach is same as above, just the syntax is a bit different
const extractedFeatures = (({name, gender}) => ({name, gender}))(person);
console.log(extractedFeatures); //{name: 'Peter Parker', gender: 'male'}

In this example, we can see that we are extracting the features at the time of receiving the object as a parameter.


Advantages of Destructuring:

  1. Simplified code: Destructuring simplifies code by reducing the amount of code needed to extract values from arrays and objects. It can be used to extract values from complex data structures with fewer lines of code.

  2. Improved readability: Destructuring can improve code readability by making it easier to understand which values are being extracted from an array or object.

  3. Avoiding repetitive code: Destructuring can help avoid repetitive code by allowing you to extract multiple values at once, instead of repeating the same code for each value.

  4. Renaming variables: Destructuring also allows you to rename variables when extracting values from objects, which can help clarify code and prevent naming conflicts.


Keep practicing the questions to make this concept in your practice so that you don't find it overwhelming when you incur something related to destructuring, and with practice, you will also build an intuition about where to use destructuring and where not to.

That's a wrap!!

Happy Coding😃