Introduction to Destructuring in JavaScript

Introduction to Destructuring in JavaScript

ยท

5 min read

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'
}

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;

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;

Let's log the new variables on the console:

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

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"

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

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'
  }
};

We can destructure a nested object like this:

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

console.log(potions)
// output - 'Severus Snape'

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 }

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'];

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'

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

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

console.log(name);
// 'Ron Weasley'

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'

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

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"

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

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"]

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"

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

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! ๐Ÿ‘ฉโ€๐Ÿ’ป