Quick Question About JavaScript Algorithms and Data Structures ES6 14/29

Hello all,

I’m going through the JavaScript Algorithms and Data Structures section of Free Code Camp and I come across something that I was hoping someone with a bit more familiarity with JavaScript could explain to me.

In exercise 14/29 of ES6 we destructure the stats object to use the attributes as arguments in an arrow function. I understand logic and was able to figure out the solution, however I’m left wondering how does the browser know where to get these attributes from as it’s not specifically declared in the solution code.

I’ve tried adding in another object with different values to the same attributes, placing these classes above and below the originally set object but the browser always passes the lesson so I assume it’s getting the correct attributes from the intended object?

How does the browser know which object to get these attributes from?

1 Like

I’ve tried adding in another object with different values to the same attributes, placing these classes above and below the originally set object but the browser always passes the lesson so I assume it’s getting the correct attributes from the intended object?

It is using the stats object that is declared above. It is referring to it by name so it knows which one to get. This is happening invisibly, behind the scenes as part of the test. If you change the min and max values in the stats object, the test will fail.

Thank you Kevin.

Just to clarify. If I were to take this code and try to run it in an IDE on my desktop with the extra objects I made, would I need to add more specificity into where my function was pointing to get the intended object or would it choose a particular object based on other factors (first declared, last declared, etc.) ?

The function doesn’t know and doesn’t care where that data is coming from. All the function knows is “I will get a reference to an object and I should pull the properties ‘min’ and ‘max’ off that object and store them into local variables with those names”. It doesn’t care if the object had a name in the outer scope and doesn’t care. It doesn’t care if there are other properties. All it knows or cares about is that this is an object with those properties.

const myObj1 = {
  max: 2,
  min: 1,
}

const myObj2 = {
  max: 12,
  min: 3,
}

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

console.log(half(myObj1))
// 1.5

console.log(half(myObj2))
// 7.5

console.log(half({max: 127, min: 21}))
// 74

Does that help?

2 Likes

Thank you Kevin.

Now that I can see how the variable interacts with the objects in your example in the bottom half I can see why it works and that a random object isn’t just being selected at random.

Yeah, it seems like “magic” since that function call is happening in the test, where you can’t see it.