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

Tell us what’s happening:
My question is quit simple, in the code below supposing if we have 2 objects with the same properties names, how dose JavaScript knows what object we want to destructure ?

PS : i runned the test on freeCodeCamp editor and it says that my solution is correct ( half(stats) should be 28.015). I tried the same code (with only one object) on a HTML file and loged the result and it gives me this error :

Exercice.html:52 Uncaught TypeError: Cannot destructure property 'max' of 'stats' as it is undefined.
    at half (Exercice.html:52)
    at Exercice.html:55

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 stats2 = {
max: 30,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.5,
average: 35.85
};
// Only change code below this line
const half = ({max, min}) => (max + min) / 2.0; 
// Only change code above this line

Your browser information:

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

Challenge: Use Destructuring Assignment to Pass an Object as a Function’s Parameters

Link to the challenge:

Hi adel,
welcome to the FCC forum. This baffled me too at first. The thing is, this part here only defines a function:

const half = ({max, min}) => (max + min) / 2.0; 

JavaScript gets the information which object to destructure from the function call. Which would look like this:

half(stats);

If I run your code in the browser console, it works as well. Without seeing your html file, it is hard to tell …

1 Like

michaelsndr Thank you so much, you’re absolutly right… it makes more sens and the script works perfectly now on my html file after giving the name of the object as an argument for the function. Amazing!
Thanks a lot again for clearing up this to me.

1 Like

Also, note that this line:

const half = ({max, min}) => (max+min) / 2.0;

is taking the first parameter (in this case, the first object), and deconstructing that. If more than one object were to be passed in, for whatever reason, that syntax says “take the first parameter and deconstruct that one.”

2 Likes