Destructing question

Here is this code:

const stats = {
  max: 56.78,
  standard_deviation: 4.34,
  median: 34.54,
  mode: 23.87,
  min: -0.75,
  average: 35.85
};
const half = (function() {
  "use strict"; // do not change this line

  // change code below this line
  return function half({max, min}) {
    // use function argument destructuring
    return (max + min) / 2.0;
  };
  // change code above this line

})();
console.log(stats); // should be object
console.log(half(stats)); // should be 28.015

How max and min in the following code:

return function half({max, min}) {

get the values from stats variable?

If you look at the example on this challenge, it shows how you can destructure a function’s parameters. The global variable stats is passed to the function named half. You are just destructuring the stats object which was passed to the function.

It is a shorter way of writing the returned function as:

  // change code below this line
  return function (stats) {
    const {max, min} = stats;
    return (stats.max + stats.min) / 2.0;
  };
  // change code above this line
1 Like

Thanks for the answer.

But how the object {max, min} understands that it has to do descructuring on the stats objects? I could have other global variables there as well.

in the same way you pass anything in a function, you call the function passing the object as an argument. Thi function will work with any object that has a min and max property

2 Likes

I see. Thanks for the answer.