Home » Tutorials » JavaScript » ES6 features: Destructuring Assignment

ES6 features: Destructuring Assignment

ES6 features: Destructuring Assignment

Prior to ES6, there was no direct way for us to assign multiple properties or value of the array into multiple variables.

Assuming we have an User object:

const User = {
    name: 'Joe',
    nationality: 'Malaysian',
    age: 30
}

Prior to ES6, to assign the variable to the properties of the User object, we do like this:

const name = User.name;
const nationality = User.nationality;
const age = User.age;

Starting from ES6, we can use a new feature called Destructuring Assignment to destructure properties of an object or element of an array into individual variables.

Object Destructuring Assignment

Here’s an equivalent assignment statement using the ES6 Destructuring Assignment:

const { name, nationality, age } = User;
// output: name = 'Joe', nationality = 'Malaysian', age = 30

The name, nationality, age variables will be created and assigned the values of their respective values from the User object.

Give new variable names in the assignment

Is not necessary to use back the same variable name from the object’s properties, you can give new variables names in the assignment:

const { name: newName, nationality: newNat, age: newAge } = User;
// output: newName = 'Joe', newNat = 'Malaysian', newAge = 30

Nested Object Desctructuring

Here is how to extract the property values of nested object:

const Users = {
    user: {
        name: 'Joe',
        nationality: 'Malaysian',
        age: 30
    }
}

const { user: { name: newName, nationality: newNat, age: newAge } } = Users
// output: newName = 'Joe', newNat = 'Malaysian', newAge = 30

Array Destructuring Assignment

Assuming that you have a function that returns a list of grades:

function grades() {
    return [20, 40, 60, 80, 100];
}

Similar to object descructuring assignment, you can write the code as follow:

const [E, D, C, B, A] = grades();
// console.log(B);
// output: 80

Using Descructuring Assignment with Rest Parameter

In some situation, we may want to omit some of the element in an array, assuming we want to omit scores 30 and below:

const score = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
function removeFailed(list) {
    const [,,,, ...arr] = list;
    return arr;
}

const passScore = removeFailed(score);
console.log(passScore);
// output: [40, 50, 60, 70, 80, 90, 100]

We can access the value from the array at any index with desctructuring with commas. In the example above, we use 4 commas to access to value 40 from the array, and then use Rest Parameter …arr to get the rest of the value and pack them into an new array named arr.

Please be noted that, the Rest Parameter must be the last element in the argument list.

Thanks to ES6, we can assign multiple properties or value of the array into multiple variables for now. 🙂

You may also interested in: