To destructure an object sent into the function

Hello,
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters

I don’t understand how is done the link between parameters and the object because “stats” as name of object does not appear in half const.

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

The destructing is not exclusive to just the stats object. The destructing will work any time you call this half function with an object that has the max and min properties.

Ok but if there is two obeject with max and min properties, which object will be selected ?

the one you pass to the function

in the code snippet, only the object is declared and the function body, the function isnt called. To call the function you pass properties(if it requires such). In the case it is designed to work with an object which has keys named “min” and “max”.
You can do as follow:

console.log(half(stats))    //returns 28.015
console.log(half({min: 5, max: 10}))     //return 7.5

recall that functions are reusable code

2 Likes

You call a function like this

half(theObjectThatIWantToUse)

and the specific object that you use as an argument when you call the function will be the object that is destructured.

Ok, thank you all,
I had forgot how to use the arrowed function.

Yeah, sometimes the different looking style of function declaration can throw off your mind.

Exacly :wink:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.