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 alength
property (string.length
) that you can access when you create a newString
.Assume a
String
is always passed togetLength(str)
function. Use the destructuring assignment to assign thelength
property ofString
tolen
.
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.