Use Destructuring Assignment to Assign Variables from Objects1

Use Destructuring Assignment to Assign Variables from Objects1
0

#1

Tell us what’s happening:

why it’s not passing the third test case?

third test case: destructuring with reassignment was used

Your code so far


function getLength(str) {
  "use strict";

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

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

}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 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

You could actually do this in one liner.

There is no need to save str.length into leng. Try to deconstructure length into len using const.


#3

@shimphillip is exactly right. Its the intermediate step of assigning the value into your object o, then using that to populate len, that is causing your code to fail. Instead, simply use str to populate len directly, using destructuring .


#4

I believe you may have unintentionally ommitted the th in length.

@snowmonkey I sadly must disagree. Assigning to a variable, while pointless, should not cause the code to break. :slightly_smiling_face:


#5

look again - the OP assigns str.length to o.leng

The reassignment, when removed , passes.


#6

Thank you guyz for quick response. But I m still not able to figure out the one line code. See this below code is laso not passing the third test case.

function getLength(str) {
“use strict”;

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

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

}

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


#7

ES6

const {length : len}=str;

is the same as:

standard:

const len = str.length;

In first example, you’re assigning len a value of a property length of the string named ‘str’. Thus when you assign str, it finds its length. And how you’re gonna check that? Here’s how: Instead of using string str put some other string in function with its own, different value and console log it.

standard:

function getLength(str) {
  "use strict";
var ttt="ojha";//another string
  // change code below this line
  const {length : len}=ttt;//find a length of string
  console.log(len); //display it at console
  return len; // you must assign length to len in line

}

Destructuring objects - how do this code calculate the str length we are not using str.length?
#8

Thanks man. cool explaination.