DEV Community

Star
Star

Posted on

Use Destructing Assignment to Pass an Object as a Functions Parameters

Rather than destructuring the object within the function, this method aims to show that it can be destructured as an argument.

const profileUpdate = (profileData) => {
  const { name, age, nationality, location } = profileData;

}
Enter fullscreen mode Exit fullscreen mode

This shows that profileData has a function of const { name, age, nationality, location } = profileData;. This breaks the data submitted as an argument with a function-const.

const profileUpdate = ({ name, age, nationality, location }) => {

}
Enter fullscreen mode Exit fullscreen mode

In this second example, we see the the same const profileUpdate but this time it destructures the incoming data within the argument and has a set of empty function brackets(? I don’t remember what they’re called right now) for the in-argument function to propogate it’s result and return it back to profileUpdate.

I hope I understood all this correctly, this was too easy and it makes me worry that I misunderstood something.

Prompt - Use destructuring assignment within the argument to the function half to send only max and min inside the function.

Original

const stats = {
  max: 56.78,
  standard_deviation: 4.34,
  median: 34.54,
  mode: 23.87,
  min: -0.75,
  average: 35.85
};

// Only change code below this line
const half = (stats) => (stats.max + stats.min) / 2.0;
// Only change code above this line
Enter fullscreen mode Exit fullscreen mode

Submitted Code

const stats = {
  max: 56.78,
  standard_deviation: 4.34,
  median: 34.54,
  mode: 23.87,
  min: -0.75,
  average: 35.85
};

// Only change code below this line
const half = ({ max, min }) => (max + min) / 2.0;
// Only change code above this line
Enter fullscreen mode Exit fullscreen mode

Here, max and min are being destructured by the const half, but then it also adds them together and divides them by 2.0. I don’t feel the prompt specifies enough that it is requesting for half of the max and min, rather it just asks to send only max and min, not half of max and min.

Top comments (0)