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}) => (max + min) / 2.0;
// Only change code above this line
How does the function “half” know, that it should take max and min
from stats? What if there was another Object with exactly the same propertys called max and min?
Thanks for your help!!
The function would be called like half(stats) and the half function would look for the max and min keys inside of the stats Object and then it would use them as arguments for the function.
Because when the function is called, you’re saying it should be called with an object that has the properties min and max. You’ve written the function to say it should use the min and max properties on that object: it doesn’t “know” anything, you’ve just said exactly what it should do.
If you pass it an object that doesn’t have the properties min and/or max, or those values aren’t numbers, the function won’t work. Same as if you write
function multiply(a,b) {
return a * b;
}
multiply doesn’t “know” a and b are numbers, it just tries to run the body of the function regardless of what it gets given.
We’ll, if you passed an object with the properties min and max to the function, then the function will do exactly what you’ve specified it to do: average the min and max values.
I just went through this tutorial and had the same question. To get it set in my own head I played around with this a little. second object made called stats2 and then below there are two calls (console.log) to the function of half one passing the stats object the second passing the stats2 object. This is how the function understands what object to work with.
Excuse the formatting, I’m sure it will come out terrible.
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.