I don't understand this: Use Destructuring Assignment to Assign Variables from Objects

I don't understand this: Use Destructuring Assignment to Assign Variables from Objects
0

#1

Tell us what’s happening:

I get the temperature right ( 79) and this test fails: “destructuring with reassignment was used”.

I don’t understand this concept. Please help. Thank you.

Your code so far


const AVG_TEMPERATURES = {
  today: 77.5,
  tomorrow: 79
};

function getTempOfTmrw(avgTemperatures) {
  "use strict";
  // change code below this line


  const tempOfTomorrow = avgTemperatures.tomorrow ; // change this line
  // change code above this line
  return tempOfTomorrow;
}

console.log(getTempOfTmrw(AVG_TEMPERATURES)); // should be 79

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-objects


#2

Okay, you haven’t used destructuring here at all, which is the main point of the exercise. So until you do that, the tests will always fail

Putting that aside, what happens if I run this function like so:

getTempOfTmrw({today: 50, tomorrow: 56})

Which is completely valid. I can clearly see the temperature tomorrow is 56, but your code will return 79. Also what happens if I delete the AVG_TEMPERATURES object (given its just there to check the function works)?


#3

OK - there are two issues with your solution.

The first is that you are supposed to use Destructuring Assignment
const tempOfTomorrow = AVG_TEMPERATURES.tomorrow is not Destructuring Assignment

The other is you are acting on the global variable AVG_TEMPERATURES. You are supposed to be using the parameter passed to that function


#4

Hi!
I don’t understand what destructuring accomplishes and how to use it. I looked at videos and still don’t get it :frowning: Can you explaing to me, please?


#5

Shorthand for creating objects and assigning properties to them:

const myObj = { foo: 1, bar: 2 }

Shorthand for accessing properties on objects (x and y are 1 and 2) and assigning them to variables:

const { foo: x, bar: y } = myObj;

See how they are the inverse of one another.


For comparison:

const myObj = new Object();
myObj.foo = 1;
myObj.bar = 2;

Then

const x = myObj.foo;
const y = myObj.bar;

#6

Hi! Thank you for your help. I finally got it. The inverse part and reassignment was not making sense :smiley:


#7

:wink: It is a little bit strange, and definitely quite confusing at first sight - hopefully it’s a bit easier to grok when you see it’s just basically the opposite of the object creation.