Use Destructuring Assignment to Assign Variables from Objects review

Use Destructuring Assignment to Assign Variables from Objects review
0.0 0


Tell us what’s happening:
A little help with my code in this challenge. Thanks very much

Your code so far

function getLength(str) {
  "use strict";

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

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



Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:


Hah, I saw a few people were having problems with this challenge. It is incredibly confusing

So you want to just return len at the end, you don’t return things in like that, destructuring doesn’t change how JS works.

Strings are converted to objects to do useful things to them in JS, and they have a property length (among other things). So you can use destructuring to grab things from that object. So here, I’m saying I want the properties length, valueOf and constructor from the string “foo” (which is the value of test)

const test = "foo";
const { length, valueOf, constructor } = test;

Which is the same as:

const test = "foo";
const length = test.length;
const valueOf = test.valueOf;
const constructor = test.constructor;
> length
> valueOf() # valueOf is a function, not just a value
'foo' # it won't actually return this in practise, it'll blow up because the String object has already been garbage collected so the reference no longer exists
> constructor
[Function: String]

With the destructuring, you’re grabbing the properties by their name. You can also assign them to another name (maybe you’re using those values a lot and the word constructor is too long, you just want c instead or something):

const test = "foo";
const { length: l, valueOf: v, constructor: c } = test;

So you get

> l
> v()
'foo' # again, in practice this won't work
> c
[Function: String]

This is an ultra-confusing challenge because it assumes a knowledge of how JS works that you’re not likely to have, b. uses something as an example that I honestly can’t see any real-world use for, and c. forces you to use something (assigning inside destructuring) that is not used very much. It’s a really bad example to use: destructuring is very, very useful, but this is not a good display of that usefulness in any way at all really.


length is an inbuilt Js property of str that can be assigned to len
so all you need to do is
property length of str is assigned to local variable len