Tell us what’s happening:
My solution works just fine. No issue passing the tests.
I just don’t understand why this solution works.
How does the interpreter know to access the stats object for the max & min properties?
Suppose there was another object with max & min properties named stats2. How would the interpreter know to assign the max & min properties from stats or stats2?
I don’t believe I’ll ever use this syntax. I think it has the potential to confuse readers of my code w.r.t. the originating object of min & min.
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
};
// Only change code below this line
const half = ({max, min}) => {
return (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/84.0.4147.125 Safari/537.36.
Challenge: Use Destructuring Assignment to Pass an Object as a Function’s Parameters
Yes, if you develop in JS, you will see and use this notation a lot. It is very common. It just looks “weird” because you are not used to it.
I think it has the potential to confuse readers of my code w.r.t. the originating object of min & min.
But in your code, there is only one variable min and max - the ones inside the scope of the function. The others are properties on the object.
If you had variables in the outer scope, it would cause no confusion to JS - it would know to use the ones in closest scope. It might cause a little potential confusion to the user if they didn’t look closely. That’s why it’s considered a bad practice - called “shadowing variables”. But that is not the case here - they are just props on the object and anyone with experience with destructuring (read: any experienced JS developer) would figure it out. But it’s still best to avoid. For example, code analyzers like Sonar would flag this as a “code smell”.
But you definitely need to learn this notation - I guarantee that you will see it a lot. I use it many, many times a day. But yeah, when I first learned it, it looked weird to me too. But now, it’s second nature.