JavaScript Destructuring
As part of learning React, I'm also trying to shore up my JavaScript skills. Thankfully, the React: Getting Started pluralsight course also offers a modern JavaScript crash course. These are my notes from when I tried to understand JavaScript's Destructuring feature.
Note that you can run the sample code on a JavaScript tester website, like say the JSComplete Playground.
So, the JavaScript destructuring assignment syntax allows you to get just the properties you want from an object. It seems to be like a shortcut for getting to the properties of an object. For example:
const customerInfo = {
firstName: "Dino",
lastName: "Bansigan",
emailAddress: "myemail@email.com",
website: "dinobansigan.com"
}
const getFullName = ({firstName, lastName}) => {
return firstName + " " + lastName;
}
console.log(getFullName(customerInfo));
In the code above, you can see how I have created a customerInfo
object. Then next is a function called getFullName
that takes a firstName
and lastName
parameter. These parameters are destructured from the customerInfo
object.
If you look at the last bit of code where I call console.log
, you can see that instead of passing in parameters customerInfo.firstName
and customerInfo.lastName
, all I had to do, was pass in the customerInfo
object. JavaScript through the destructuring feature is smart enough to know to use the firstName
and lastName
properties from the customerInfo
object.