5 Interesting Uses of JavaScript Destructuring

Original link: dmitripavlutin.com/5-interesti…

Periodically reviewing the JS code I write, I find that deconstruction is everywhere. Getting properties of objects and accessing the contents of arrays are common operations. Deconstruction makes these operations very straightforward. In this article, I’ll look at five ways in which JS deconstruction differs from common usage.

1. Swap variables

A common way to interact the values of two variables requires an extra variable. Here’s a simple example:

let a = 1;
let b = 2;
lettemp; temp = a; a = b; b = temp; a; // => 2 b; / / = > 1Copy the code

Temp is a temporary variable. In this example, the value of variable A is stored, the value of b is assigned to A, and the value of temp is assigned to B. Deconstruction makes it very easy to swap the values of variables without resorting to a third temporary variable:

let a = 1;
letb = 2; [a, b] = [b, a]; a; // => 2 b; / / = > 1Copy the code

[a, b] = [b, a] is a deconstruction operation. On the right side of the equals sign, an array [b, a] is created with the corresponding value [2, 1]. The first value of the array, 2, is destructively assigned to A and the second item, 1, is destructively assigned to B. Even though this method still creates a temporary array, deconstructing assignments is a very efficient and simple way to exchange values of variables. There are no limitations to this approach. You can also exchange more variable values at the same time, such as:

let zero = 2;
let one = 1;
lettwo = 0; [zero, one, two] = [two, one, zero]; zero; //=> 0 one; //=> 1 two; / / = > 2Copy the code

You can swap any number of variable values, but it’s more common to swap two variable values.

2. Access arrays

There’s an array, and the array might be empty. One requirement is to access an array element at any position and return a default value if the position is empty. In general, one might use the length property of the array:

const colors = [];
let firstColor = "white";
if(colors.length > 0) { firstColor = colors[0]; } firstColor; / / = >"white"
Copy the code

Fortunately, array deconstruction can achieve the same effect more quickly and efficiently:

const colors = [];
const [firstColor = "white"] = colors; firstColor; / / = >"white"
Copy the code

const [firstColor = “white”] = colors; The first element of the Colors array is assigned to the variable firstColor. If there are no elements in the array at zero, white will be assigned to firstColor as the default. Array deconstruction is very flexible. If you want to access only the second element of the array, the method looks like this:

const colors = [];
const [, secondColor = "black"] = colors; secondColor; / / = >"black"
Copy the code

Put a comma to the left of the deconstructed expression: the first element of the array is ignored. The elements with subscript 1 in the Colors array are deconstructed and assigned to the variable secondColor.

3. Immutable operation

From the time I started using React, and later Redux, I was forced to start writing code that followed immutable rules. It was a bit awkward at first, but LATER I realized the benefits of this approach: it made it much easier to deal with one-way data flows. The immutable rule forbids modifying objects. Fortunately, deconstruction can help you do this while adhering to the immutable principle. Use deconstruction with the rest operator to remove the first element of the array:

Const Numbers = [1, 2, 3]; const [, ...fooNumbers] = numbers; fooNumbers; //=> [2, 3] numbers; / / = > [1, 2, 3]Copy the code

The destruct operation [,…fooNumbers] = numbers creates a new array fooNumbers that contains all elements of numbers except the first element. The numbers array is not changed; this approach follows the immutable principle. In addition, you can use the same method to delete an object’s properties while following the immutable principle. Delete the foo property of the big object as shown below:

const big = {
    foo: "value foo",
    bar: "value bar", } const { foo, ... small } = big; small; //=> { bar:"value bar" }
big;    //=>{ foo: "value foo", bar: "value bar" }
Copy the code

The above method combines deconstruction with the object expansion operator to create a new object, Small, that contains all the properties of the Big object except the properties of foo.

4. Deconstruct iterable values

In the previous sections, it was all a deconstructed array. In fact, deconstruction can be applied to all iterables. Many primitive types and objects are iterable, such as arrays, arrays of classes, strings, sets, and maps. For example, you can split a string into a single character:

const str = "cheese";
const [firstChar = ""] = str; firstChar; / / = >'c'
Copy the code

Of course, deconstruction is not limited to the native, iterative types. Destructuring can be applied to any object that implements the Iterable Protocol. Movies contains a list of movie objects, as shown below. When we want to deconstruct movies objects, we get the string title of the movie. To do this, we first need to define an iterator:

const movies = {
    list: [
        { title: "Heat" },
        { title: "Interstellar" },
    ],
    [Symbol.iterator]() {
        let index = 0;
        return {
            next: () => {
                if (index < this.list.length) {
                    const value = this.list[index++].title;
                    return { value, done: false };
                }
                return { done: true} } } } } const [firstMovieTitle] = movies; console.log(firstMovieTitle); / / = >'Heat'
Copy the code

Movies objects implement an iterator by defining the symbol. iterator method. This iterator iterates over the title property of all movies. We followed the iterative interface implementation on movies objects to get titles by deconstructing movies. For example, we get the title of the first movie: const [firstMovieTitle] = movies; . The limit of deconstructive usage is that there is no limit.

5. Deconstruct dynamic properties

In my experience, deconstructing an object’s properties is far more common than deconstructing an array. Deconstructing objects looks pretty simple:

const movie = { title: "Heat" };
const { title } = movie;
title;    //=> Heat
Copy the code

const { title } = movie; A variable title is created and the value of movie.title is assigned to it. One of the things that surprised me when I first learned about object deconstruction was that you don’t need to know the static names of properties in advance. You can deconstruct an object by dynamic property names. To understand how dynamic deconstruction works, let’s write a greeting function as an example:

function greet( obj, nameProp ) {
    const { [nameProp]: name="Unknow" } = obj;
    return `Hello, ${name}! `; } greet({ name:"Batman" }, "name");    //=>    Hello, Batman!
greet( {}, "name" );    //=>    Hello, Unknow!
Copy the code

Greet () is called with two parameters: an object and a property name. Greet () const {[nameProp]: name=” unknown “} = obj; Read the name of the dynamic property using brackets [nameProp]. The name variable receives the value of the dynamic property. Better yet, you can specify a default value unknown in case the attribute does not exist.

6. Summary

Deconstruction helps you access object properties and array elements more quickly and easily. In addition to basic usage, array deconstruction makes it easy to swap variables, access array elements, and do things that follow immutable rules. JavaScript offers more possibilities because you can implement custom deconstruction logic by extending iterators.