**How does destructuring work?**

How does destructuring work?

Challenge: Use destructuring assignment within the argument to the function half to send only max and min inside the function.

Solution:

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

My questions:
1 - How does program understand that max, min , should be gotten from stats?
2 - What’s difference between const [a, b] = stats; and const {a, b} = stats;?

What I tried, that didn’t work?

const half = ({max, min} = stats) => (max + min)/2.0;
ERROR: Destructuring should be used.
const half = ([max, min] = stats) => (max + min)/2.0;
ERROR: 
half(stats) should be 28.015
Destructuring should be used.

Link to the challenge:

This is not doing what you are expecting it to do.

When the half function is called:

half(stats);

the stats objects is passed to the function, so you only have to destructure the properties you want out of the object passed. JavaScript knows it can extract min and max out with the following syntax:

const half = ({max, min}) =>

because when you write {max, min} that is the destructuring syntax for extracting properties from an object. Since stats was an object passed to the function, this is valid syntax to capture the two properties.

The syntax [max, min] would not work here , because that is the syntax you would use to extract the first two elements of an array passed to the function. Since stats is not an array, it would not work.

2 Likes

Understood) Thank you!
Also, how do you know with what arguments the half function is called?
I can’t seem to find any clue about it in the challenge’s page.

Here’s another example for the destructuring:

const myPersonObject = { name: "Joe", age: 30 };
const { name } = myPersonObject;
console.log(name); 
// "Joe", because there is a property "name"

const myPersonArray = ["Jane", 40];
const [ firstElement ] = myPersonArray;
console.log(firstElement); 
// "Jane", because it is the first element

const [ , secondElement ] = myPersonArray;
console.log(secondElement); 
// 40, because you skip the first element (",")
1 Like

look at the tests
it says half(stats) should be 28.015

that means that the function is being called as half(stats)

1 Like