Destructuring is a way to break a complex structure into simpler parts.
Many times we want to assign pieces of a complex data structure to variables.
Before it was tedious to do, but with JS Object Destructuring it is much simpler to do.
Let’s learn with an Example
Let’s see how bad it is to repeat the same code to access the required data from the structure.
const mytask = {
procedure: 'addition',
numbers: {
a: 4,
b: 5,
c: 6
}
};
function calculate() {
return mytask.numbers.a + mytask.numbers.b + mytask.numbers.c;
}
Let’s Check with old way
Without destructuring, we would do something like:
const mytask = {
procedure: 'addition',
numbers: {
a: 4,
b: 5,
c: 6
}
};
function calculate() {
const a = mytask.numbers.a;
const b = mytask.numbers.b;
const c = mytask.numbers.c;
return a + b + c;
}
Let’s Check with destructure
Now let’s see how we would do this the modern way, with object destructuring.
const mytask = {
procedure: 'addition',
numbers: {
a: 4,
b: 5,
c: 6
}
};
function calculate() {
const { a , b , c } = mytask.numbers;
return a + b + c;
}
Let’s Check with default values
Another feature is default values. You don’t have to check if some properties exist before destructuring. Implement this.
const mytask = {
procedure: 'addition',
numbers: {
a: 4,
b: 5,
c: 6
}
};
function calculate() {
const { a , b , c , d = 0 } = mytask.numbers;
return a + b + c + d;
}
Let’s Implement with changing Names
If you don’t want to use the same names as in the structure. Let’s change them.
const mytask = {
procedure: 'addition',
numbers: {
a: 4,
b: 5,
c: 6
}
};
function calculate() {
const { one: a , two: b , three: c , four: d = 4 } = mytask.numbers;
return one + two + three + four;
}
Let’s Implement with destructure
We can even destruct inside a destructure. This can be useful to reduce a bunch of code in more complex situations. Let’s check it out.
const mytask = {
procedure: 'addition',
numbers: {
a: 4,
b: 5,
c: 6
}
};
function calculate() {
const { procedure , numbers: { a , b , c , d = 0 } } = mytask;
if(procedure === 'addition')
return a + b + c + d;
return null;
}
How is the experience with Object Destructuring?
Top comments (0)