Use Destructuring Assignment to Assign Variables from Objects on 1 line?

Tell us what’s happening:
can’t understund how to reassign in one line…

// running test
destructuring with reassignment was used
// tests completed

Your code so far


function getLength(str) {
  "use strict";

  // change code below this line
  const {length:len = 0} = {length:str.length}; // change this  
  // 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/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-objects/

const {length:len = 0} = {length:str.length};

Two issues: on the left side, you are trying to assign a value to len. If you took destructuring out of this, what you’re doing would be similar to:

const len = 0 = { something }

This is not what you want. The left side needs to be the property you’re extracting from the object on the right side.

const { length } = { someobject }

is saying "Get the length property from someobject and assign its value to a constant with the name length.

const { length: len } = { someobject }

is saying "Get the length property from someobject and assign its value to a constant with the name len.

Now, on the right side, you do not need to try to create a new object. When you’re destructuring, whatever is on the right side is going to be checked for the property that is referenced on the left side. Since all strings have a length method, simply putting str on the right side will give you the result you want.

1 Like

Thx for you quick reply and help! i fix my code :slight_smile:

1 Like