ES6: Use Destructuring Assignment to Assign Variables from Objects help

I am trying to solve the Destructuring Assignment challenge and I am stuck.

Can someone explain the destructuring assignment concept and walk me through the challenge please?


Challenge:

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

Starting 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'));

Thanks.

Hello,

I will go through the destructuring assignment concept itself, then cover up the challenge afterwards:

Destructuring assignment: a reintroduction

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

“Come again? I don’t get your MDN copy-paste explanation…”

You see, arrays have values, and objects contain properties.

We usually access the array values and object properties like so:

// Object example reference:
let car = {
  type: "Hatchback",
  color: "red",
};
// access car values:
console.log(car.type);  // output: Hatchback
console.log(car.color); // output: red

// Array example reference:
let transaction = [5, 10, 3, 6, 8];
// access transaction values:
console.log(transaction[0]); // output: 5
console.log(transaction[1]); // output: 10
console.log(transaction[2]); // output: 3

And sometimes, we would like to assign those values into variables:

// ref: car object
let car_type  = car.type;
let car_color = car.color;

// ref: transaction array
let first_transaction  = transaction[0];
let second_transaction = transaction[1];

Now, the JavaScript community got jealous from Python (py already implements assignment destructuring) and decided to embrace the practice of clarity and an easier way to access data:

// instead of:
let type  = car.type;
let color = car.color;

// you can now do:
let { type, color } = car;
// access values:
console.log(type);  // output: Hatchback
console.log(color); // output: red

// instead of:
let first_transaction  = transaction[0];
let second_transaction = transaction[1];

// you can now do:
let [ first_transaction, second_transaction ] = transaction;
// access values:
console.log(first_transaction[0]); // output: 5
console.log(second_transaction[1]); // output: 10

“But what if I want to rename type or color differently when I destructure the car object?”

Good catch, you can do that using the following syntax:

// instead of:
let { type, color } = car;

// you can do:
let { type: car_type, color: car_color } = car;
// access values:
console.log(car_type);  // output: Hatchback
console.log(car_color); // output: red

Along the way while using the assignment destructuring syntax you will find many gotchas, which you will need to read the syntax documentation carefully and patiently to get over them. I’d recommend MDN web docs - Destructuring assignment after understanding the basics.

“But why the extra syntactic sugar?”

Because this way, you won’t need to repeat the destructured expression. It will also make some things easier to read. Consider the following example:

On the server-side, sometimes you need to get the username, email and password from a request object – let’s say the user is registering a new account – Instead of:

/** get user registration input */
let username = req.body.username;
let password = req.body.password;
let email    = req.body.email;

I can do:

/** get user registration input */
let { username, password, email } = req.body;

Or a little bit more complex, sometimes I only need certain properties from an object passed to a function: (or maybe I just want to pre-destruct the argument)

function BuildCar ({ type: model, color }) {
  console.log(model); // output: Hatchback
  console.log(color); // output: red
}

// ref: car object
BuildCar(car);
// output:
//  Hatchback
//  red

In more complex situations, this will save you an extra variable + improve readability. Now that you got this off, have a walk or a small break before going into the next section of this answer if you want. (solving the challenge)

4 Likes

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

That’s a top notch explanation about Destructuring Assigments that I was going nuts about! Thank you.

I’d also like to add the following challenge information:

If instead you want to store the values of voxel.x into a, voxel.y into b, and voxel.z into c, you have that freedom as well.

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.

That may help more people reassigning values.

AGGGGGHHHHHH!!!

This felt like it should have been easy but I ended up taking a long time to work this one out.

Key to this on is that the string is the object, once you get that the whole thing makes a bit more sense.

Also try here:

After 1.22 of watching I had the answer.

Now I feel like a bit of a dope :confused:

I’m still not getting it. Once I (finally) understood that every string is an object with property length, I came up with:

function getLength(str) {
  "use strict";

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

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

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

I feel like this should be working, but I’ve still got it wrong. I’m getting “len is not defined”. Well, duh, I’m trying to define it. What am I misunderstanding?

You’re close, you are unpacking the object and assigning the variable the other way around: (You’re probably getting "len is undefined." error as a result)

The correct syntax for assigning to new variable names:

{ unpacked_property : new_variable_name } = Object;

Read this section again: (updated)

Whoops! Yeah, that was a silly mistake. I think I had it backwards because of how you normally assign values to variables. Thanks for the clarification and all of your help on this!

This one took me a long time to complete.

Thanks to U-ways and Jcunningham77 for explaining this one in the way I needed.

AGGGGGHHHHHH!!! This felt like it should have been easy but I ended up taking a long time to work this one out. Key to this on is that the string is the object, once you get that the whole thing makes a bit more sense.

This was the key. Truly. Realizing that the str is an object and as such using length as a key:value pair to put into len was what really took FOREVER and lots of research to finally understand.