Passing an object into a function parameter with destructuring

Tell us what’s happening:
How far off am I here? Destructuring in general has been causing me a lot of problems…

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
const {standard_deviation, median, mode, average} = half(); {
// use function argument destructuring
return (stats.max + stats.min) / 2.0;
};
// change code above this line

})();
console.log(stats); // should be object
console.log(half(stats)); // should be 28.015
Your code so far


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
  const {standard_deviation, median, mode, average} = half(); {
    // use function argument destructuring
    return (stats.max + stats.min) / 2.0;
  };
  // change code above this line

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 OPR/52.0.2871.64.

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

Close. Destructuring is a way to make getting the values out of an object faster and more readable. So

const myData= {
  a: 1,
  b: 2
}

I can then call the function oldWay(myData)

function oldWay(objPassedIn) {
  // objPassedIn.a === 1
  // objPassedIn.b === 2
}

or call the function newWay(myData)

function newWay({ a, b }) {
  // a === 1
  // b === 2
}

You can also break it apart later inside the function oldWay(myData)

function oldWay(objPassedIn) {
  const { a, b } = objPassedIn
  // a === 1
  // b === 2
}

Anywhere you want to pull out properties from an object at the same time, that’s what destructuring is. The same work for arrays, because arrays are actually objects under the hood.

Hopefully that should set you in the right direction.

1 Like