Use Destructuring Assignment to Pass an Object as a Function's Parameters (question?)

Tell us what’s happening:

Got the correct answer via reading hints and researching destructuring but can someone explain this a little further? I am destructuring the constant “stats” and using two properties from it (max and min). would this have worked with preset variables that weren’t already declared in the “stats” const declaration or did ES6 recognize the max and min from the prior input of const stats.

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
  return function half({max, min}) {
    // 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 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36.

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/

Destructuring is an expression that “unpacks” values from an array, or properties from an object.

This make it convenient to “pick” only the value that are needed into a new variable.

For example:

const arr = [1,2,3,4,5];

// for example in an array I can pick the value I need, and keep the rest
[a,b, ...rest] = arr;
console.log(a) // 1
console.log(rest) // [3,4,5]

// equivalent to
const a = arr[0]; // 1
const rest = arr.slice(2, arr.length) // [3,4,5]

When dealing with objects means I can pick whatever property I want from an object

const o = {a: 1, b: 2 };

// pick the value associated with the prop 'a' from 'o'
const {a} = o;

console.log(a) // 1

// what happens if I pick a prop that is not defined in an object?
const {a, c} = o;

console.log(a) // 1
console.log(c) // undefined -> no prop 'c' inside the object

For a full list of possible usage of this operation refer to the MDN Documentation Page, is reach of practical examples.

Hope this helps :+1: