via Youtube

ES6: Object Destructuring

Md. Abu Talha
InfancyIT

--

Destructuring is a huge part of ES6. Along with arrow functions, let, and const, destructuring is probably something we are going to be using every single javascript file in our project.

When we fetch an object from API, we need to extract element for our work purpose. In older javascript style we extract each element from an object with a line. If there is 100 element of an object we to had to write 100 lines for extraction but ES6 is a big relief. It helps us to extract multiple elements from an object with a single line.

From the above example, Here is an object namedstudent A student has firstname, lastname, country and ielts_score. In the old destructuring method we need to write 4 lines of code to exact all the data but in ES6 we just need only one line.

Different Variable Names:

When we want a different variable name for an object key we only need the colon operator.

{object_key : new_variable_name } = object

Assigning Default Value:

When we assign a variable corresponding to a key that does not exist on the destructured object it will give us undefined. That's why we need to assign default value sometimes.

{ object_key = default_value } = object

Nested Destructuring:

Here in our main student object, we have a nested object and there are some scores. when we want to extract these key we need to follow nested Destructuring rules.

nestedObject : {nested_key_1, nested_key_2, nested_key_3, ……}

--

--