Origin of short synax Destructuring Assignment?

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

Link to the challenge:

Hello! Welcome to the forum :grin:!

You’re misinterpreting it :stuck_out_tongue:.

The interpreter knows which one to use because the developer tells it which:

const stats = {
  min: 1,
  max: 9
};

const stats2 = {
  min: 10,
  max: 19
}

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

console.log(half(stats)); // Output: 5
console.log(half(stats2)); // Ouput: 14.5

In other words, it destructures the object you tell it to :slight_smile:.

1 Like

Oh…on the call
derr

1 Like

I don’t believe I’ll ever use this syntax.

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.

2 Likes

Thanks for the wider context…its super helpful