Destructuring: object & function - 03

Object & function:

In some cases, you can destructure the object in a function argument itself.
Consider the code below:

const profileUpdate = (profileData) => {
  const { name, age, nationality, location } = profileData;
}
This effectively destructures the object sent into the function. This can also be done in place:

const profileUpdate = ({ name, age, nationality, location }) => {}
When profileData is passed to the above function, the values are destructured from the function parameter for use within the function.


More example:

const obj1 = {
      name: 'mozahedul',
      title: 'student',
      favoritePlace: 'Mecca',
      address: {
        city: 'Dhaka',
        District: 'Rangpur'
      }
    };

function person({
      name,
      title,
      favoritePlace = 'London'
    }) {
    console.log(`My name is ${name}, title is ${title}, and favorite place is ${favoritePlace}`);
    }

person(obj1);
    
// Result: My name is Mozahedul, title is student, and favorite place is Mecca.

Post a Comment

Previous Post Next Post