Object and Array destructuring in javascript

Object and Array destructuring in javascript

·

3 min read

What is destructuring?

Destructuring means unpacking values from objects or arrays or properties from objects and assigning it to separate variables. Destructuring can be done with objects, arrays and even nested objects.

Destructuring in arrays

The values that need to be extracted from the source are specified on the left hand side . Let us see an example below:

let x,y;
[x,y]=[6,8];
console.log(x); //6
console.log(y); //8

The code above gives us a rough idea about array destructuring where the values 6 and 8 are assigned to the variables x and y.

Let us take another examples that demonstrates destructuring in arrays.

const arr= ["Shelby","Ryan","Jane","Mike"];
var [first,second]=arr;
console.log(first); //Shelby
console.log(second); //Ryan

The variables first and second are assigned the values “Shelby” and “Ryan” respectively by specifying the array name .

We can also skip certain array elements while destructuring assignment. The code below demonstrates the same :

const arr= ["Shelby","Ryan","Jane","Mike"];
var [first,,third]=arr;
console.log(first); //Shelby
console.log(third); //Jane

Assigning properties of an object directly to variables:

({x,y}={x:10,y:20});
console.log(x); //10
console.log(y); //20

Here the properties of the object are directly assigned to the variables x and y.

The Rest operator(…)

Now let us know about the use of Rest operator(…) in array destructuring from a simple example:

const arr= ["Shelby","Ryan","Jane","Mike"];
var [first,,...third]=arr;
console.log(first); //Shelby
console.log(third); //Jane,Mike

The code above assigns the first element of the array to first, skips the second element of the array ( as represented by , ,) and then returns the rest of the elements into the array third. Thus, first will contain “Shelby” and third will contain [“Jane”, “Mike”] .

Swapping variable values using destructuring assignment

Generally the values of two variables are swapped with the help of another temporary variable. However, with destructuring assignment, the values of two variables can be swapped without the need of a temporary variable. The code below demonstrates how variables are swapped using destructuring assignment:

var [first,second]=["abc","def","ghi","jkl"];
console.log(first); //abc
console.log(second); //def
//swapping
[first,second]=[second,first];
//after swapping
console.log(first); //def
console.log(second); //abc

Destructuring assignment in functions

Destructuring assignments can be used to return values from an array by calling a function and assigning the values to the respective variables.

function myfunc(){
        return  ["Shelby","Ryan","Jane","Mike"];
}
var [first,second]= myfunc();
console.log(first); //Shelby
console.log(second); //Ryan

The code above assigns the first two values of the array returned by myfunc() i.e Shelby and Ryan to first and second respectively.

Destructuring in nested objects


const person = {
    name: "Jane",
    age: 30,
    address: {
        city: "Los Angeles",
        country: "USA"
    }
};

// Destructure nested objects
const { name, age, address: { city, country } } = person;

// Output the extracted values
console.log("Name:", name); //Name: Jane
console.log("Age:", age); //Age: 30
console.log("City:", city); //City: Los Angeles
console.log("Country:", country); //Country: USA

The code above contains a nested object with the object person containing properties name, age and address. Address itself is an object with properties city and country. The values of name, age , city and country are extracted from the object with the help of destructuring and the individual values of the properties are printed out.

Another example demonstrates the use of destructuring

const person = {
    name: "Jane",
    age: 30,
    address: {
        city: "Los Angeles",
        country: "USA"
    }
};

// Destructure nested objects
let {address:{city: abc, country: def}}= person;

// Output the extracted values
console.log("City:", abc); //City: Los Angeles
console.log("Country:", def); //Country: USA

The code above assigns the values of city and country to abc and def respectively with the help of destructuring.

Conclusion

In summary, JavaScript's destructuring feature is a potent tool that makes it possible to extract values from objects or arrays, resulting in code that is more succinct and expressive. Destructuring allows for more coding freedom and efficiency when handling nested objects, assigning properties from objects to variables, unpacking values from arrays, or even just switching variable values. Developers can design more understandable and maintainable JavaScript applications by learning and applying destructuring techniques.