Use-destructuring-assignment-to-assign-variables

Tell us what’s happening:

tried destructuring… can anyone please check the code below

Your code so far



function getLength(str) {
  "use strict";

  // change code below this line
  const length = { len : str.length };// change this
  const{ len } = length;
  // 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 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36.

Link to the challenge:

Please give a hint if any one solved this challenge

You’re very close but I think you’ve misunderstood the syntax

Let’s look at the example again:


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.’


We want to get the field length and copy the value into len.

Does this help?

const { str : len }= length;

return len.length;

i tried this am i missing something here ?

With const length = { str: len}; there are two problems:

  1. You’re destructuring on the wrong side of the equals sign
  2. You’re destructuring the wrong thing

The right hand side of the equals sign should be = str; That’s the object we want to destructure, and that’s where it needs to be.

Then, we want to get the property of str called length and copy it into a variable called len, so the object side should be {length: len}

This is really important so make sure to read the example again thoroughly to understand it!

1 Like

thanks to you it is working…
I am confused about one more thing here~

function getLength(str) {
const {length : len} = str ; // change this

return len;
}
console.log(getLength(‘FreeCodeCamp’));

HERE the function is returning the length of the string… " const {length : len} = str "
IS ‘length’ a pre-defined function (str.length) ?
is it a property we have on string ?

Yes, all strings have a length property by default, you can rely on it

1 Like

Can we use other pre-defined functions like ( split , join , splice etc…) on arrays and strings as properties in destructuring ?

1 Like

Yes that’s right, the functions associated are actually properties of the objects (and arrays and strings) inherited via their prototypes

That’s in a way why we can type str.length or str.split(), split is a property of strings, and is also a function we can call - adding the () actually calls this function

Of course you wouldn’t necessarily want to destructure out the functions in this way, but you can

1 Like

Thanks @vagrahb for all your questions and @gebulmer awesome explanation.
Its very informative :slight_smile: cheers, Monika.