Hi Fellow FreeCodeCampers!
I’m new to JavaScript and working through the list of assignments on free code camp. I’m on the lesson -
ES6: Use Destructuring Assignment to Assign Variables from Objects.
Now there are 3 examples they give, all which makes sense to me:
Example #1:
var voxel = {x: 3.6, y: 7.4, z: 6.54 };
var x = voxel.x; // x = 3.6
var y = voxel.y; // y = 7.4
var z = voxel.z; // z = 6.54
Example #2:
const { x, y, z } = voxel; // x = 3.6, y = 7.4, z = 6.54
Example #3:
const { x : a, y : b, z : c } = voxel // a = 3.6, b = 7.4, c = 6.54
Now the problem given is:
Use destructuring to obtain the length of the input string str, and assign the length to len in line.
This is the original code to start with:
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’));
Ok - so now I’m confused. If I simply use .length, I get the error that I haven’t used destructuring to obtain the length. I have two questions,
#1 why would we use destructing to do this when there is a simple answer like .length
#2 how do we use destructing for this?
// make this change
const len = str.length;
In the example the only thing I see are ways to assign properties of an array to a const variable, but I’m having difficulty even starting. I don’t understand how this would be used to get the length of a variable.
Anyone have any suggestions on how to break this problem down or explain what I am missing?