Object destructuring helps us assign values of arrays or properties of objects to variables. This feature helps us unload the content of objects and assign it to variable names making it easy to access the content without the need to involve the object names. Let us look at some examples to see how it works.

Destructuring Javascript Objects

Let’s create an object employee that holds properties fName, lName and the age of the employee.

const employee = {
    fName: 'Mickey',
    lName: 'Mouse',
    age: 20
};

Now to access the values, we can use the . operator on the object.

let fName = employee.fName;
let lName = employee.lName;
let age = employee.age;

Now let’s use the object destructure feature to perform the same assignment.

​​let { fName, lName, age } = employee;

As you can see, the same operation can be performed in a single line. On the right side, we specify the individual variable names that should hold the property values and on the left side is the object.

In case, we specify an additional variable within the curly brackets {}, the variable will be assigned value undefined.

let { fName, lName, age, department } = employee;

console.log(department); // undefined

The object employee does not contain property department, hence the department variable will contain undefined.

Destructure arrays

We can also make use of the destructuring feature on arrays.

let numbers = [1, 2, 3, 4, 5, 6];

[num1, num2, num3, num4, num5, num6] = numbers;

console.log(num1); // 1
console.log(num2); // 2
console.log(num3); // 3
console.log(num4); // 4
console.log(num5); // 5
console.log(num6); // 6

If you want to just assign the first element to a variable, you can do it as follows:

let numbers = [1, 2, 3, 4, 5, 6];

[num1] = numbers;

console.log(num1); // 1

Using rest operator while destructuring an object

We can also make use of the rest operator while destructuring the object. The rest operator variable will be assigned to all the remaining values in the object.

const employee = {
    fName: 'Mickey',
    lName: 'Mouse',
    age: 20
};

let { fName, ...restInfo} = employee;

console.log(fName); // Mickey
console.log(restInfo); // {lName: 'Mouse', age: 20}

Destructing function arguments

The object destructuring can also be done when passing an object to a function call. The property of the object gets assigned to the arguments of the function. For example,

const employee = {
    fName: 'Mickey',
    lName: 'Mouse',
    age: 20
};

function fullName({ fName, lName }) {
    console.log(fName); // Mickey
    console.log(lName); // Mouse
};

fullName(employee);