Please help! ES6 destructing and ressignment

Please help! ES6 destructing and ressignment
0

#1

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

This doesn’t work!!! why???

function getLength(str) {
  "use strict";

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

  // change code above this line
  
  return len; // you must assign length to len in line

}

console.log(getLength(‘FreeCodeCamp’));


#2

const { x : a, y : b, z : c } = voxel // a = 3.6, b = 7.4, c = 6.54
You may read it as “get the field x and copy the value into a,” and so on.


#3

Because you are not using destructuring. All you have done is assigned an object with a property named “len” and a value of the str’s length to a variable named len.

If you want to destructure an object, the object must appear on the right side of the = operator. Then on the left side you would write your object syntax as follows. The following example assumes we have an object named myObj that has one property named “myProp”.

/* start with defining myProp - this could very well be something passed
into a function, but for this example, I am declaring it here */
const myObj = {myProp: 'a string value'};

/* now let's say I want to use desctruturing to create a new variable 
with the value of myObj's myProp value, then I could write the following: */

const {myProp: myPropValue} = myObj;
console.log(myPropValue);  // displays 'a string value' to the console 

Another way to think about it is:

const {objectProperty: newVariable} = object;
console.log(newVariable);
/* the above code will display the object's objectProperty value because
newVariable has the destructured value of the object's property named "objectProperty"  */

#4

Thanks @randelldawson
???is this right then?.this is also not working!

function getLength(str) {
“use strict”;

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

// change code above this line

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

}

console.log(getLength(‘FreeCodeCamp’));


#5

The object goes on the right side of the = operator. You have {x: str.length} on the right side. The object here is simply str. This challenge assumes you understand the strings in JavaScript have properties which technically means strings are objects. I won’t go into the why of that right now, but all you need to know is str is the object being destructured. Then on the left side of the = operator you write your applicable {propNameToGet: newVariableName }.


#6

thank you so much @randelldawson. I got it.

function getLength(str) {
“use strict”;

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

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

}

console.log(getLength(‘FreeCodeCamp’));