Use Destructuring Assignment to Assign Variables from Objects

Use Destructuring Assignment to Assign Variables from Objects
0

#1

Tell us what’s happening:

I don’t understand this at all.

Instructions:

Consider the following ES5 code:

var voxel = {x: 3.6, y: 7.4, z: 6.54 };
var x = voxel.x; // x = 3.6
var y = voxel.y; // y = 7.4
var z = voxel.z; // z = 6.54

Ok awesome. An object with key value pairs, that we are then assigned to global variables. I know this! But then…

Here’s the same assignment statement with ES6 destructuring syntax:

const { x, y, z } = voxel; // x = 3.6, y = 7.4, z = 6.54

What? Thats not at all what the previous code was. First the keys don’t have values. So x shouldn’t be 3.6. Second no global variables are being assigned to anything. This is literally just equal to this:

const Obj = {x,y,z};

Aka an object with declared keys (no values).
I am so stuck. Read the ntructions like 20 times and I still have 0 clue about what I have to do.

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


#2

Ok. I took a break. Calmed downed, and read the MDN entry on Destructuring assignment. Saw some videos and I kind of got it.

Correct me if I am wrong. This ES6 feature is used to assign object values to external variables. Yes?
Anyhow, this is my new code and its still wrong:

function getLength(str) {
  "use strict";

  // change code below this line
  const length = {x: str.length};
  const {x : len} = length; // change this
  // change code above this line

  return len; // you must assign length to len in line

}

console.log(getLength('FreeCodeCamp'));

Says:

destructuring with reassignment was used

with an X next to it.


#3

Hi

While the solution is fairly easy the instructions are a little baffling. You are not alone in being confused by the challenge.

What they want is for you to assign the length property of str to a local variable len using destructuring assignment, all on one line.

This is their example that pertains to the challenge solution

const { x : a, y : b, z : c } = voxel // a = 3.6, b = 7.4, c = 6.54

//property x of voxel is assigned to local variable a

so you need to do
property length of str is assigned to local variable len


ES6 - Use Destructuring Assignment to Assign Variables from Objects
#4

Thank you! Now I get it!

I can see how this aught be helpful now.


#5

Please show this code bro.


#6

this code was super well explained if you arent getting it dot just ask for the answer track the variables and try to understand the syntax for what is going on.


#7

You’re a godsend! Thanks so much for helping me understand the syntax :slight_smile:


#8

thanks! now the instructions are much easier to understand.