Use Destructuring Assignment to Assign Variables from Objects review

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
3
> 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
3
> 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.

9 Likes