Search code examples
javascriptobject-destructuring

Destructuring Assignment to Pass an object as function's parameter


I am learning Javascript on freeCodeCamp, and I came across passing an Object as a function Parameter through restructuring Assignment

I was asked to

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

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 solution doesn't make sense to me since it doesn't even mention stats. How come does it work? Can someone explain it please. thank you in advance.


Solution

  • Of course the function doesn't mention stats explicitly - the function cannot know the name of a variable that might be passed to it

    const stats = {
      max: 56.78,
      standard_deviation: 4.34,
      median: 34.54,
      mode: 23.87,
      min: -0.75,
      average: 35.85
    };
    
    const half = ({ max, min }) => (max + min) / 2.0;
    
    console.log(half(stats));

    The signature of your function ({ max, min }) reads like this:

    From any (first) argument passed to this function, assume it's an object that has max and min properties. Make those available under their name as local variables inside the function body.