Destructing helps to write less code and easy way to access the properties in JavaScript.
Object destructuring.💔
Suppose we have an object literal.
let obj={
name:'sai',
show:true
}
How can we access the properties in Object?
- The answer is we are using dot notation to access the object properties
Like we need to use obj.propertyname or obj['propertyname']
let's see the same thing using object Destructuring
Have you seen in object Destructuring we are accessing the same property in an easy way instead of writing dot notation?
Array Destructuring
Let's see an example
How can we access elements in an array?
- The answer is we are using its location like 0,1,2,3etc
The second thing we can access using arr['0']
Now we can access the same elements using Array Destructing instead of using its location every time.
How can we use Destructuring in functions?
let's see the example
I'm passing the object as an argument to the function.
The Same thing with Destructuring
In above code, we are destructuring the object in the function parameter itself.
Have you seen how much less code we write to access the same thing?
Now we are moving to level deep
Nested destructuring💣
It is bit easy instead of we don't need to write obj.show.items to access the items property.
Hope you guys enjoyed!!!!! If you have any doubts feel free to ask.
Happy coding........
Top comments (2)
One of the overlooked but incredibly useful ways to use destructuring is in the interface of a function. Think of a function with a signature such as:
When writing client code that invokes this function, the developer has to either remember the correct order of the parameters or spend time looking it up.
With destructuring, we can write the function to take a single object as the input param:
Now the dev simply writes the function call and passes an object with the appropriately named attributes:
The order of the named parameters now doesn't matter, since as long as the names are the same the function's parameters will be automatically populated. Combine this with default values for the input parameters and you significantly reduce the effort required to use the function.
I think this one is also good!