Understand : Use Destructuring Assignment to Pass an Object as a Function's Parameters


I have a question about the answer code from the “Use Destructuring Assignment to Pass an Object as a Function’s Parameters” course.

How the function know that min and max are from stats object?


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 (({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

Link to the challenge:

It doesn’t, it has no idea, the function just expects an object that has min and max properties. As long as the object that gets passed to the function has them the function will work.


Right, it make more sense! :slight_smile:
If there is another object, with similar properties, is it gonna work? I assume that no.

EDIT : I just saw that we call the stats object here :
console.log(half(stats)); // should be 28.015 <- Obviously the object used will be stats
So, I answered my own question! :stuck_out_tongue:

I’ve another question about the half function.
Why does it end with () ?

const half = (function() {
  "use strict";
  return (({max, min}) => {
    return (max + min) / 2.0;
})(); <-----
1 Like

The whole thing is wrapped in that outer function, which executes straightaway, and the entire reason for it being there is that "use strict" at the top, and it’s purely for the benefit of the tests. () is how you signal to JS you are executing a function - myFunction would be the identifier for a function, myFunction() is telling JS to execute it. In JS you create scope by putting stuff inside functions: everything inside that outer function is contained, it doesn’t leak out, and it’s its own little environment. It’s called an immediately invoked function expression (IIFE)


I just completed this one and I’m not entirely sure why it works. I feel like this is something I will look back on in the future and be glad it exists. But right now, arrow functions are not my friend.

"const half = ({max, min}) => (max + min) / 2.0; " is the function definition. At this point stats has not been passed into the half function because it hasn’t been called.

The code is run behind the scene and the module let’s you know that half(stats) returns 28.015.

If you want to see how this works add “console.log(half(stats));” to your code and you will see 28.015 in the console.

Please do not answer two year old topics.

Thank you.