JavaScript Pills: destructuring
This is a post from a series where I share insights from my journey with JavaScript in a mini article format. See all other posts on my profile!
ES6 brought a new way to extract data from arrays and objects to different variables called destructuring. Before that, extracting from an array was done like this:
const ages = [14, 28, 47];
const age1 = ages[0];
const age2 = ages[1];
const age3 = ages[2];
console.log(age1, age2, age3);
// 14 28 47
And extracting from an object was done like this:
const person = {
name: 'Barbara',
age: 36,
job: 'Developer'
};
const name = person.name;
const age = person.age;
const job = person.job;
console.log(name, age, job);
// Barbara 36 Developer
Destructuring accomplishes the same task, but in a simpler and leaner way. Let’s go back and refactor the first example using this technique:
const ages = [14, 28, 47];
const [age1, age2, age3] = ages;
console.log(age1, age2, age3);
// 14 28 47
Wow, we turned three lines of code into one!
Observe the syntax of the second line, which is where the destructuring happens. On the left side, we use square brackets to indicate that we are destructuring an array; right there, we declare three variables at the same time, age1
, age2
, and age3
, to save the extracted values. On the right side, we indicate that these values shall be copied from the ages
array.
We did not specify the indexes from which the values should be extracted because they are no longer needed; now they implicitly follow the order of the elements in the array.
However, this does not mean we have to extract all values. You can ignore values by leaving a blank space between commas, like this:
const ages = [14, 28, 47];
const [age1, , age2] = ages;
console.log(age1, age2);
// 14 47
In the example above, destructuring skipped the second index, which was dropped.
We can follow the same logic to extract values from an object. Let’s try destructuring our previous object example:
const person = {
name: 'Barbara',
age: 36,
job: 'Developer'
};
const {name, age, job} = person;
console.log(name, age, job);
// Barbara 36 Developer
Here, the curly braces {}
indicate that the object will be destructured and the values will be stored in the name
, age
and job
variables. And on the right side, we state that the values will be copied from the person
object.
We did not specify the keys from which the values should be extracted because, by naming the variables identically to the object keys, we let the destructuring match them and automatically store the value of the key name
in the variable name
. It’s like doing const name = person.name
.
It's worth noting that this operation does not alter the original array or object — it just copies its values to other variables.
That’s all for today and see you next time ❤