Need help with ES6: Use Destructuring Assignment to Assign Variables from Arrays

because the variables are being created anew so they need to be declared with const or let, you don’t use const or let when assigning a value to an already existing variable. In the editor a and b have already been declared at the top, so you don’t need to declare them again, nolet or const is neede.

why is this creating you so much confusion? with let [c, d] = [1,2,3,4] only the first two items in the array are being destructure, the others are ignored. It dosn’t make a difference how many ignored items there are. With a situation like let [c, d] = [1, 2] there are just 0 ignored items.

the variables hold values that are numbers, it is exactly the same. You use variables to have reusable code, but the behaviour is the same using a literal or a variable. Don’t panic if I say that there could be objects, functions, other arrays, in the array and it would work the same, it is just that numbers are easy to type and make easy examples. The elements in the array could be whatever, it doesn’t matter. Destructuring takes the elements in the array and store them in variables. The way that it is written is frankly incohomprensible, but that is the evolution of a programming language, new versions add features that let you write less, but you loose cohomprensibility.

because they are literally that data type, you can look at it and see that it is a string, number, array, object. It is to distinguish those from values held in variables.

it is not considered destructuring
that’s exactly an example of destructuring, with the caveat that it will work exactly like only if x and y are already declared variables, if they are new you need to put a let or const in front of the line

destructuring is one of the new features of the language that have obscure syntax, don’t try to intepret them using previous knowledge. Think of it as a totally new thing, with its own syntax. To the right of the assignment operator there is an array, to the left of the assignment operator a completely new grammar rule that you can’t compare in any way to something you already know.

I should probably clarify: the literal syntax I was referring to would be constant literals. Any value in square brackets is also an array literal, just not necessarily a constant. In fact the part to the left of a destructuring assignment is never constan.

Sorry for the confusion, I’m probably too befuddled to be much help today :-/

Following is not a “literal” (nowhere in this code do you use the JS array literal syntax you would be used to):

let myArr = new Array(3);
myArr.push(1)
myArr.push(2)
myArr.push(3)

For comparison, an array literal. It means you can create and populate an array by just typing some values seperated by commas inside square brackets:

let myArr = [1,2,3]

Following is not a “literal” (nowhere in this code do you use the JS object literal syntax you would be used to):

let myObj = new Object();
myObj.foo = 1;
myObj.bar = "a";
myObj.baz = false;

For comparison, an object literal. It means you can create and populate an object by just typing some key/value pairs seperated by commas inside curly braces:

let myObj = { foo: 1, bar: "a", baz: false };

It’s a symbolic illustration of what you might imagine “an array” to be, which can be used instead of manually writing out the instructions of what to do to create and populate your array.

ASCII has a [ and ] characters, put them together, it’s a bit like a box. Put values in-between them (and you need a separator, so use ,) and now you have a box with stuff in it in order, that’s a fair representation of arrays. You then use that symbolic illustration to define arrays in your code. When you draw your box and assign it to myArr, the interpreter/compiler is gonna do the steps in that first code block for you, you don’t have to write them out.

1 Like

Well, that’s a good question, and if I knew the answer to that, I would likely be able to home in on that specific issue and try to resolve it. But up to this point, I’ve tried to explain the things that are causing me confusion, and the more information provided in the responses, the more overwhelmed and confused I get, maybe due to “information overload.” (I’ve also watched several youtube videos and read in the Eloquent Javascript book…more info, less understanding, more confusion…)

One thought is that I am trying to learn ES6, when the truth is, I have no real understanding of ES5.

Also you said:

The way that it is written is frankly incohomprensible, but that is the evolution of a programming language, new versions add features that let you write less, but you loose cohomprensibility.

So maybe I am trying to comprehend something that is incomprehensible…but I’m not sure how I would be able to effectively use destructuring if I am not able to comprehend it.

you just need to get that

let [x, y] = arr;

let you do the same than

let x = arr[0]
let y = arr[1]

which is, store elements of the array in variables

in the second code snippet, you say which elements go in which variables using bracket notation and indexes

in the first code snippet you say which elements go in which variable using position

so the x is in the first position in the target list, it will have the first element of the array (the one at index 0), the y is in the second position in the target list, it will have the second element of the array (index 1)

Ok I think I do understand this. Just not how it relates to the exercise.

The exercise is about using destructuring. You can’t do the exercise without knowing how destructuring work, it relates pretty much…

Now we have two variables
a, and b, and we want to swap their values, for whatever reason. (for example, in creating a Fibonacci series, swapping variables values is something that is done)

we could do this:

let temp = a;
a = b;
b = temp;

but there is a way to make it in on one line.
let’s do it in two, first

// let's create an array to hold the two variables
let arr = [a, b];
// now let's use destructuring to swap the values
[b, a] = arr;

([b, a] = arr is doing b = arr[0]; a = arr[1];)
so the first variable, which is a, get assigned the first value in the array, which is the value of b, and the variable b get assigned the value of a. (when creating the array the values have been copied inside the array, so you don’t need a middle variable to do the swap)

We could do it without the arr variable, creating the array in place:

[b, a] = [a, b]

(this is doing b = [a, b][0]; a = [a, b][1]; - not exactly this, as it wouldn’t be possible for variables changing value, but similar enough)
to the left of the assignment operator there is the target list, to the right of the assignment operator the array we just created (we need it only once so we can just do this instead of using a variable to hold it), and this array hold the starting values of the variables. It happens the same thing than before, just in one line.

Honestly, I think swap is an absolutely lousy first lesson on array destructuring. The bits about empty elements are also completely unnecessary. The whole challenge needs to be rewritten.

3 Likes

yeah, many people find a wall in the ES6 section…
I don’t know what could be proposed as destructuring application, tbh, but this is totally confusing as first thing

1 Like

Thanks for this, I was just wondering if any practical uses of array deconstruction exists

Whenever you have an array of known shape, it could be more readable to break out its parts into variables.

Imagine an array of coordinates like so:

const triangle = [
  [0, 0],
  [2, 0],
  [1, 1],
  [0, 0]
];

Let’s use forEach to just loop through and log the coordinates.

// no assignment
triangle.forEach((coords) => {
  console.log(`x: ${coords[0]}, y: ${coords[1]}`);
});

// assignment without destructuring
triangle.forEach((coords) => {
  const x = coords[0];
  const y = coords[1];
  console.log(`x: ${x}, y: ${y}`);
});

// assignment with destructuring
triangle.forEach((coords) => {
  const [x, y] = coords;
  console.log(`x: ${x}, y: ${y}`);
});

// parameter destructuring
triangle.forEach(([x, y]) => {
  console.log(`x: ${x}, y: ${y}`);
});

All four of the above do the same thing, it’s just up to you to decide which is most readable. Destructuring, in my opinion, is mostly there to allow us to make our code more explicit (x, y is a lot easier to understand than coords[0], coords[1]), which is a good thing.

1 Like

This thread helped me to understand what was actually going on in this exercise after I solved it :slight_smile:

Question:
Have we created 1 unnamed array in this context? Or is it thrown away immediately since we never assigned them?

EDIT:

I learned in another thread that the [b, a] = [a, b] gets transpiled to regular JS since it’s ES6-only syntax, so I guess that answers that.

I wouldn’t get too caught up in worrying what the compiler is doing. Using a language with garbage collection means we don’t need to think about memory.

2 Likes

the right-hand side is an unnamed array, but the left-hand side is just destructuring syntax

2 Likes

Yeah I spaced out there and didn’t bother to correct my question. Sorry about that.

Def not losing any sleep over it but was genuinely curious. But I guess this really gets transpiled down to regular JS with assignments?

@padunk That was so useful. Thanks so much!

1 Like

This is what finally helped me understand this mess.