Assume, that we have an object:
const obj = {
a: 'a',
b: 'b',
};
And we want to get b
property. We have a simple way:
obj.b; // 'b'
// or
obj['b']; // 'b'
but, we can use a JavaScript ES6 thing called destructuring
- but what’s this?
Destructuring assignment
Most used JavaScript data structures are Array
and Object
.
Array let us store data in ordered collection, syntax looks like:
const student = ['John', 'Doe'];
Object allow us to create an entity, where we can store data by keys, for example:
const student = {
firstName: 'John',
secondName: 'Doe',
};
And when we’ll need to use Array
or Object
, in most common cases, we’ll need all data or only some of them.
The New ES6 feature gives us syntax sugar which allows us to in an easy way get only fields that we’ll need. It works really well when we’re facing big objects, or arrays and need only a few fields.
Object destructuring
Let’s get back to our example student
object.
const student = {
firstName: 'John',
secondName: 'Doe',
};
A classic way of getting one of the field value is
student.firstName; // John
// or
student['firstName']; // John
The new syntax allows us to do it in my opinion - a cleaner way.
const { firstName } = student;
firstName; // John
The same thing we can do with secondName
const { firstName, secondName } = student;
firstName; // John
secondName; // Doe
One what we need to remember is that we need to know what keys objects store.
Also, it isn’t a problem to change the key name on the fly.
const { first: firstName, second: secondName } = student;
first; // John
second; // Doe
But what if we will have a more complex structure? Maybe like this?
const student = {
firstName: 'John',
secondName: 'Doe',
parents: {
father: {
firstName: 'Joe',
secondName: 'Doe',
},
// ...
},
};
To get father
field, we can as in old way - do it in dot or bracket notation or new way
const { parents: { father: { firstName } } = student;
firstName // Joe
Summary
Getting variables using destructuring makes our life a bit easier. It looks nicer than the normal way and makes code reading easier.
For now, I’m using them more than the old way, and what do you think about it?