Array/Object  Destructuring in Javascript

Array/Object Destructuring in Javascript

Why Is Array/Object Destructuring So Useful And How To Use It

·

6 min read

What is destructuring?

The idea of restructuring is to take an object or an array and convert it into smaller objects or elements or smaller variables. So let's take a simple example

//array of alphabets
const alphabets = [ 'A','B','C','D','E']
//array of numbers
const numbers = [ 1,2,3,4,5]

//get the first element of the alphabet array
const a=  alphabets[0]
//get the second element of the alphabet array
const b =  alphabets[2]
console.log(a)
console.log(b)

As you can see we are trying to access the elements of an array using their index positions, but this is kind of clunky to do there's an easier way to do this with the help of Destructuring

Let's consider the alphabets array js const alphabets = [ 'A','B','C','D','E']

//trying to access elements using object restructuring

const [ a ,b ] = alphabets

console.log(a)

console.log(b)

As you see we get the same output A and B but, how does this actually work?

So the idea behind destructuring is to take the element you want to destructure and put it on the right side of the equal sign so essentially it says destructure the alphabets array and on the left side we specify the variable name that is the name of the elements which are to be returned, along with the square brackets. If you further want one more element it can be done as such

const [ a ,b ,c] = alphabets 
console.log(a)
console.log(b)
console.log(c)
//The output will be A B C

If you want to skip any elements you can do it as such : js const [ a ,b ,,d] = alphabets //skips the 3rd element that is c

The spread operator

This operator is a new & unique operator provided by ES6 it consists of three dots (...). The spread operator allows you to spread out elements of an iterable object such as an array, map, or set.

Example: const citrus = [lemon,orange,lime]; const combined = [apple,watermelon,kiwi, ...citrus]; console.log(combined);

Output:

[ apple,watermelon,kiwi,emon,orange,lime]

Spread is a feature in JavaScript that allows an iterable such as an array or a string to be expanded in places where multiple elements or characters are expected. This is often used to spread the contents of an array into individual arguments when calling a function or to spread an object's properties into a new object.

For example, consider the following code:

let numbers = [1, 2, 3];
let max = Math.max(...numbers);
console.log(max); // Outputs 3

Here, the spread operator (...) is used to spread the elements of the numbers array into individual arguments for the Math.max function. This is equivalent to calling Math.max(1, 2, 3).

Spread can also be used to merge two arrays or objects together. For example:

let a = [1, 2, 3];
let b = [4, 5, 6];
let c = [...a, ...b];
console.log(c); // Outputs [1, 2, 3, 4, 5, 6]

let objA = { a: 1, b: 2 };
let objB = { c: 3, d: 4 };
let objC = { ...objA, ...objB };
console.log(objC); // Outputs { a: 1, b: 2, c: 3, d: 4 }

Spread can also be used to shallowly copy an array or object, which creates a new object or array with the same elements or properties as the original. This is useful for creating a new object or array that can be modified without affecting the original.

let arr = [1, 2, 3];
let copy = [...arr];
console.log(copy); // Outputs [1, 2, 3]

let obj = { a: 1, b: 2 };
let copy = { ...obj };
console.log(copy); // Outputs { a: 1, b: 2 }

It is important to note that spread only performs a shallow copy, meaning that if the original array or object contains nested arrays or objects, the copy will contain references to the same nested arrays or objects as the original. This means that modifying the nested arrays or objects in the copy will also modify them in the original.

What is object destructuring?

Object destructuring is a feature in JavaScript that allows you to extract values from an object and assign them to variables. This is useful for extracting data from complex objects or for simplifying code by assigning values to variables with more descriptive names.

Object destructuring is a feature in JavaScript that allows us to extract specific properties from an object and assign them to variables with a concise syntax. This is especially useful when working with large objects that have many properties that we do not need to use.

To destruct an object, you first need to define a destructuring assignment. This is done by using curly braces to enclose a list of variables that you want to assign values to. Then, you use the assignment operator (=) to assign the values to the variables.

To destructure an object, we use the following syntax:

const { property1, property2, ... } = object;

This will extract the specified properties from the object and assign them to variables with the same name. If we want to assign the properties to variables with different names, we can use the following syntax:

const { property1: var1, property2: var2, ... } = object;

We can also destructure nested objects by using the same syntax:

const { property1: { nestedProperty1, nestedProperty2, ... }, property2, ... } = object;

If we want to extract all properties from an object, we can use the spread operator (...):

const { ...rest } = object;

We can also set default values for properties in case they do not exist in the object:

const { property1 = "default", property2, ... } = object;

Example:

const user = { name: "John", age: 30, email: "john@example.com" };

const { name, age, email } = user;

console.log(name); // "John" 
console.log(age); // 30 
console.log(email); // "john@example.com"

In this example, we are extracting the values for the name, age, and email properties from the user object and assigning them to the variables name, age, and email.

You can also specify default values for the variables in case the object does not have a property with the corresponding name. For example:

const { name = "Anonymous", age, email } = user;

console.log(name); // "John" 
console.log(age); // 30 
console.log(email); // "john@example.com"

In this case, if the user object does not have a name property, the variable name will be assigned the default value "Anonymous".

You can also use destructuring to extract values from nested objects. For example:

const user = { name: "John", age: 30, email: "john@example.com", address: { street: "123 Main St", city: "New York", state: "NY" } };

const { name, age, address: { street, city, state } } = user;

console.log(name); // "John"
 console.log(age); // 30 
console.log(street); // "123 Main St" 
console.log(city); // "New York" 
console.log(state); // "NY"

In this example, we are extracting the values for the name and age properties from the user object, and the values for the street, city, and state properties from the address object.

Object destructuring can be very useful for simplifying and cleaning up your code, especially when working with complex data structures. It allows you to easily extract and assign values to variables, making your code more readable and maintainable.

It can also be used in a variety of situations, such as extracting data from an API response or passing multiple parameters to a function. It can help us write more concise and readable code by reducing the amount of repetitive code we need to write.


Hope you have gained some basic understanding about destructuring in Javascript , see you next time !