Destructuring assignment is the syntax of ES6 that allows us to “unpack” arrays or objects into a bunch of variables. The two most popular data structures in JavaScript are Objects and Arrays.
Objects allow us to combine many pieces of information into a single entity, and arrays will enable us to store ordered collections.
Destructuring also works excellently with complex functions with many parameters and default values.
JavaScript Object Destructuring
To destructure an object in JavaScript,
- Destructuring source: the data to be destructured. For example, a right-hand side of a destructuring assignment.
- Destructuring target: a pattern used for destructuring. For example, a left-hand side of a destructuring assignment.
Let us see the example of Object Destructuring in ES6.
// app.js const Student = { firstName: 'Krunal', lastName: 'Lathiya', university: 'GTU', enrollno: 110470116021 }; const { firstName, lastName, university, enrollno } = Student; console.log(firstName); console.log(lastName); console.log(university); console.log(enrollno);
First, we defined the object, and then we destructure that object into four different variables. Then, we logged that four different variables.
It is called a “destructuring assignment” because it “destructurizes” by copying items into variables.
It does not destroy the object. So we can still log that object. It does not modify. It stays the same.
Output
Basic assignment
// app.js const o = {p: 21, q: true}; const {p, q} = o; console.log(p); // 21 console.log(q); // true
Assignment without declaration
The variable can be assigned its value with destructuring separate from its declaration.
// app.js let a, b; ({a, b} = {a: 1, b: 2}); console.log(a); // 1 console.log(b); // 2
Array Destructuring in Javascript
Let us define an array and then restructure it into individual variables.
// app.js const pupil = ['krunal', 'lathiya', 'GTU']; const [krunal, lathiya, university] = pupil; console.log(krunal); console.log(lathiya); console.log(university);
Output
Ignore some array items
We can ignore some array items while destructuring an array. Let us see the example below.
// app.js const pupil = ['krunal', 'lathiya', 'GTU']; const [, lathiya, ] = pupil; console.log(lathiya);
In the above example, we have only destructured the lathiya variable. The other two are put empty. Unwanted elements of the array can also be thrown away via an extra comma.
In the code above, although the first and third element of the array is skipped, the second item is assigned to lathiya, and the rest are also skipped.
Works with any iterable on the right-side
We can use Destructuring with any iterable, not only arrays or objects. Let’s see the below example of a string.
// app.js const data = 'AppDividend'; const [w, e, b, s, i, t, c, o, m, k, l] = data; console.log(w, e, b, s, i, t, c, o, m, k, l);
So, one string letter becomes one variable on the left side.
See the output.
That’s it.