[JavaScript – ES2015] Destructuring

The word “Destructuring” refers to the mechanism that binds variables to values (or other variables or object properties) using pattern matching.

 

1. Destructuring

Suppose you have an array or object. Destructuring allows you to retrieve and assign values to variables in a concise syntax. The description might confuse you but with examples you can grasp the idea pretty easily.

Note that when the matching is not found, “undefined” is used. It is called “fail-soft“.

 

2. Array Matching

Arrays match each other by the order (index).

The simplest example is:

let [a, , c, d] = [1, 2, 3];

// a= 1, c = 3, d = undefined
console.log(a + ', ' + c + ', ' + d);

You can swap the values very easily with destructuring.

let a = 1, b = 2;
[a, b] = [b, a];

// a = 2, b = 1
console.log(a + ', ' + b);

 

3. Object Matching

Objects matching uses the property names.

let getPerson = function () {
    return {
        firstName: "Homer",
        lastName: "Simpson",
        age: 35
    };
};

let {
    firstName: first,
    lastName: last,
    age: age
} = getPerson();

// Homer, Simpson, 35
console.log(first + ', ' + last + ', ' + age);

Be careful with the syntax. The left side of “:” is the object property name, not the variable name to be assigned.

There is a shortcut syntax if the variable name is the same as the object property name.

let { firstName, lastName, age:howOld } = getPerson();

// Homer, Simpson, 35
console.log(firstName + ', ' + lastName + ', ' + howOld);

It is useful to extract values from JSON objects.

 

4. Function Parameter Matching

One useful area of destructuring is how function parameters can be matched.

Here is the typical example of passing config object to a function.

let doWork = function (option) {
    console.log(option.url); // mysite.com 
    console.log(option.method); // get
};
doWork({url: 'mysite.com', method: 'get'})

In ES2015, you can do like this:

let doWork = function ({ url, method }) {
    console.log(url); // mysite.com 
    console.log(method); // get
};
doWork({url: 'mysite.com', method: 'get'})

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s