Destructuring Assignment to Pass an Object as a Function's Parameters in Javascript behaviour

Viewed 2433

In a course, I use destructuring:

const stats = {
  max: 56.78,
  standard_deviation: 4.34,
  median: 34.54,
  mode: 23.87,
  min: -0.75,
  average: 35.85
};

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

I first thought the right syntax would be (which also works):

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

My question is how JS knows in which object to look for min and max and what would happen in the event of another object stats2 having properties min and max as well? I don't understand the behaviour of the code in that case.

2 Answers

When you call the method half you are writing like this,

half(stats);

So, JS knows the object you passed for half method. Therefore js will look for min, max keys in the passed object if you declare the half method like this,

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

For another object stats2, you would again call the half method the following way,

half(stats2);

Lets say you have 2 params for half method like,

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

Now if you call the half method with both your stats and stats2 object,

half(stats, stats2);

It will first take the min and max from stats and try to find foo and bar from stats2.

half is an arrow function. Now, to use half that you defined, you would need to pass an object like that half(myObject). When half receives this myObject it takes the min and max values out of it. If the provided object does not contain these values, then it will substitute the missing value with undefined.

To answer your question, JS will look for min and max only in that object that is passed to your half function. Therefore, other objects that are defined outside the scope of half will not be touched.

Related