Destructuring in JavaScript

Destructuring in JavaScript

Why do We Need Destructuring?

There are many situations where one can face the operation of destructuring in JavaScript. Destructuring implies the function of breaking down a whole entity into numerous properties. As you may already guess, this is what you do all the time when working with data.

Base Cases

There are mainly two structures that you may come across, Arrays and Objects. These are two main tools that you need for manipulating data. Let us start with the easiest one.

How does Destructuring in JavaScript work?

First of all, we will examine arrays in JavaScript. An Array in JavaScript is considered as an iterable data structure. This means that you can easily loop over any given array at any given time. Let us see an example.

let arr = [1,2,3];
for(let i in arr) {
//will print "1 2 3"

About Collecting Data in JavaScript

For example, you know that your function needs to get an integer and an array. Let’s just assume that your goal is to determine if the first argument exists in the given array. For the sake of example, imagine that the length of the array is dependant on the actions of each user of your webpage. So if the situation persists, you may get a ton of numbers, each located in a variable. It is time to do the math and find out the result. What would you do? The answer is, you could use the spread operator. This operator is a multifunctional one, as it can destroy and create arrays. Let us see the solution.

let targetNumber = 1;
let arrNumOne = 1;
let arrNumTwo = 2;

function findIfExists(target, ...array) {
    for(const element of array) if(element === target) console.log("exists!");

findIfExists(targetNumber, arrNumOne, arrNumTwo);
//will print "exists"

What Did Just Happen?

Here, the spread operator collects the data that you pass after the target and stores them into an array called “array”. This is a very useful tool if you know how to use it. As I already mentioned, it also breaks data into pieces.

About Destructuring in JavaScript

You can destructure an array in JavaScript with the help of the spread operator. Let us see an example.

let positveNumbers = [1,2,3];
let negativeNumbers = [-3,-2,-1];
let numberZero = 0;

let union = [...negativeNumbers, numberZero, ...positveNumbers];
//will print [-3,-2,-1,0,1,2,3]

Please note that with the help of two arrays and a number, we were able to get numbers between -3 and 3 inclusive. The spread operator here acted differently. It destroyed the arrays and passed the values to the new array we defined. Notice the square brackets during the variable declaration on the fifth line. Indeed, the square brackets play a significant role in this situation, as we need a placeholder for our destructured data to land.

Make sure to check out other posts related to JavaScript.

Destructuring in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top