DEV Community

Cover image for Introduction to Destructuring in JavaScript
Sushmita Pandey
Sushmita Pandey

Posted on • Originally published at sushmita.hashnode.dev

Introduction to Destructuring in JavaScript

Hey everybody πŸ‘‹
In this article we will talk about Destructuring in JavaScript.

Destructuring syntax is helpful to unpack values from arrays and objects into variables in JavaScript. This feature was rolled out in ES6 along with many other cool features.

There are two types of destructuring - Object destructuring and Array destructuring.

Object Destructuring

Consider an Object with the properties name, age and address:

let person = {
  name: 'Harry Potter',
  age: 13,
  address: 'Hogwarts'
}
Enter fullscreen mode Exit fullscreen mode

In pre-ES6 era, we would have to create new variables and assign each attribute to them, which is a repetitive process:

const name = person.name;
const age = person.age;
const address = person.address;
Enter fullscreen mode Exit fullscreen mode

But with the destructuring assignment, we can write all the variables together surrounded by curly brackets {}, so that JavaScript can create new variables with the same names:

const {name, age, address} = person;
Enter fullscreen mode Exit fullscreen mode

Let's log the new variables on the console:

console.log(name, age, address);
// output - "Harry Potter", 13, "Hogwarts"
Enter fullscreen mode Exit fullscreen mode

Using a new Variable name

If we want to give a new name to the property of an object, we can use a colon:

const {name: personName, age, address} = person;

console.log(personName);
// "Harry Potter"
Enter fullscreen mode Exit fullscreen mode

Using default values

We can provide default values to unpacked variables, the default value will be given to the variable in case the returned value is undefined.

const {x = 10, y = 20} = {x: 5};

console.log(x, y);
// 5, 20
Enter fullscreen mode Exit fullscreen mode

Nested Destructuring

We can also destructure nested objects. As an example, let's modify the person object to include teachers:

let person = {
  name: 'Harry Potter',
  age: 13,
  address: 'Hogwarts',
  teachers: {
    potions: 'Severus Snape',
    transfiguration: 'Minerva Mcgonagall'
  }
};
Enter fullscreen mode Exit fullscreen mode

We can destructure a nested object like this:

const {
  name,
  age,
  address,
  teachers: {
    potions,
    transfiguration
  },
} = person;

console.log(potions)
// output - 'Severus Snape'
Enter fullscreen mode Exit fullscreen mode

Rest operator in object destructuring

We can use the rest operator to collect the remaining properties which have not been already picked by the destructuring pattern.

let person = {
  name: 'Harry Potter',
  age: 13,
  address: 'Hogwarts',
};

const {name, address, ...other} = person;

console.log(other);
// output - { age: 13 }
Enter fullscreen mode Exit fullscreen mode

As we can see, the properties which were not defined in the variable names on the left were collected by the variable other.

Array Destructuring

Arrays can also be conveniently destructured into new variables. Let's take an example of this array:

let student = ['Ron Weasley', 13, 'Hogwarts'];
Enter fullscreen mode Exit fullscreen mode

Instead of manually assigning each array item into a variable, we can simply unpack the variables in order:

const [name, age, address] = student;

console.log(name);
// 'Ron Weasley'
Enter fullscreen mode Exit fullscreen mode

We can also declare the variables before assignment, like so:

const [name, age] = ['Ron Weasley', 13, 'Hogwarts'];

console.log(name);
// 'Ron Weasley'
Enter fullscreen mode Exit fullscreen mode

For an array having length n on right side of the argument, if the number of variables on the left side exceed n, then the first n values will be assigned values by order and the remaining variables will not be assigned any value (they will be undefined).

Default Values

A variable can be assigned a default value, which will be assigned to the variable in case the returned value is undefined.

const [name, age, address, house = 'Gryffindor'] = ['Ron Weasley', 13, 'Hogwarts'];

console.log(house);
// 'Gryffindor'
Enter fullscreen mode Exit fullscreen mode

Swapping Variables ✨

We can use the destructuring expression to swap 2 variables! How cool is that?

let a = 2;
let b = 3;

[a, b] = [b, a];

console.log(a, b);
// 3, 2
Enter fullscreen mode Exit fullscreen mode

Without destructuring syntax, we would have to use a temporary variable to do the same thing.

Skipping Items in an Array

What if we want to ignore some of the values and only want the first and third value? This can be done by only defining variables in desired places:

const [name,,address] = ['Ron Weasley', 13, 'Hogwarts'];

console.log(name, address);
// "Ron Weasley", "Hogwarts"
Enter fullscreen mode Exit fullscreen mode

In the above example, we have 2 commas instead of just one. Comma is being used to skip values in the array.

Suppose if we wanted to only get the age, we would do something like this:

const [,age,] = ['Ron Weasley', 13, 'Hogwarts'];

console.log(age);
// 13
Enter fullscreen mode Exit fullscreen mode

Rest operator in array destructuring

The rest operator can be used in arrays too, to collect the remaining values which have not been picked.

const [name, ...other] = ['Ron Weasley', 13, 'Hogwarts'];

console.log(other);
// [13, "Hogwarts"]
Enter fullscreen mode Exit fullscreen mode

The remaining values will be collected in an array which we can use later.

Destructuring in functions

If a function returns an array, we can destructure the value into variables. Let's look at a function that returns an array:

function func() {
    return ['Albus', 'Dumbledore'];
}

let [firstName, lastName] = func();
console.log(firstName, lastName);
// "Albus", "Dumbledore"
Enter fullscreen mode Exit fullscreen mode

Nested Array destructuring

We can destructure nested arrays too by placing variables inside square brackets on the left side on the index where an array is present on the right side.

const [a, b, [c, d], e] = [10, 13, [20, 25], 9];

console.log(a, c, d);
// 10, 20, 25
Enter fullscreen mode Exit fullscreen mode

That's it for this article! If you like this post please share it with your friends 😊 For any questions feel free to ping me on Twitter.

Happy coding! πŸ‘©β€πŸ’»

Top comments (0)