ES6: Use Destructuring Assignment to Assign Variables from Objects help

Solving the destructuring assignment challenge

I think most people are confused partially because the lesson and challenge itself can be a bit unclear for new JavaScript programmers.

Use destructuring to obtain the length of the input string str, and assign the length to len in line.

What the challenge is trying to say here:

The String global object contains a length property (string.length) that you can access when you create a new String.

Assume a String is always passed to getLength(str) function. Use the destructuring assignment to assign the length property of String to len.

Can you now solve the challenge using the given code snippet?

function getLength(str) {
  "use strict";

  // change code below this line
  const length = 0; // change this
  // change code above this line

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

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

If not, I don’t blame you, what makes this challenge unpleasantly confusing is the starting code snippet. Here is a better starting code snippet:

function getLength(str) {
  "use strict";

  // change code below this line
  const len = str.length; // change this
  // change code above this line

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

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

Now try to solve the above using the given challenge explanation; Use the destructuring assignment to assign the length property of String to len instead of accessing the str.length property and assigning it to len.

We’ve done something similar with the car’s example in the reintroduction section. Give it a couple of shots before reading the previous section again.

Goodluck.

2 Likes