Why is this useful? : destructuring assignment to assign variables from arrays

I’ve completed the challenge correctly, but I feel like the test example is more confusing than the description. When would code written like this ever have more utility/ be more readable than if you were just reassigning the variables? Hoping to understand instead of just checking off the boxes (or circles in this case). Thanks in advance!

Your code so far

let a = 8, b = 6;
// Only change code below this line
[a,b] = [b,a];

Challenge: Use Destructuring Assignment to Assign Variables from Arrays

Link to the challenge:

I would agree that in practice you probably would never do this particular example :slight_smile: But I guarantee that you would do a ton of destructuring, it’s awesome and more readable way to write a code in my opinion. Definitely an essential skill nowadays

1 Like

Thanks for the quick response! I’m sure it is useful, but that’s what makes the example so frustrating: I still have no idea what the actual utility is. Do you have any quick examples or links to something a beginner could understand? I’m working at it but there’s still a bit of a gap between my knowledge and being able to learn straight from the MDN documentation. Thanks again~

My favorite use of destructuring is emulating named parameters.

function chop({ string, maxLength }) {
  return string.slice(0, maxLength);

chop({ string: 'hello', maxLength: 2 }); // 'he'

It forces the function caller to specify the arguments with a name, making the code clear in many cases.

If it had been done with standard positional parameters, then it’s not really clear to the caller if it should be in this order, or what exactly the value 2 specifies.

I don’t know, maybe not a great example.

1 Like

Yeah, this exercise is pretty trivial, I admit; assigning two variables to an array and using destructuring syntax to reverse them isn’t something you’re likely to be doing in the “real” coding world. But array destructuring as a concept is a useful piece of modern Javascript development, and learning it is going to save you at least a few ‘huh?’ moments like the ones I have experienced :slightly_smiling_face:

For example, you might want to split a url like example.com/fakething/123 into its constituent parts, then grab just the hostname. Well you can do this by splitting the string into an array, then using destructuring to just pick the first element:

const [hostname] = url.split('/');

The syntax is much cleaner (to my eyes anyway) than the alternatives would be.

Also of note, React uses the pattern extensively in its useState hook, where you’ll see a lot of this type of syntax:

const [counter, setCounter] = useState(0);

(Don’t worry if the above doesn’t make semantic sense yet, the point is just that modern frameworks have widely adopted array destructuring, so definitely good to learn!)

Hope that helps!

1 Like

In a few challenges past this one, you will learn about destructuring function parameters. That is where it is very useful. For example, let’s say I have the following problem.

You are told to create a function that accepts an array with 3 elements. The first element is the price of an item, the second element is the quantity of the item, and the third element is an extra fee that is attached to the total regardless of quantity. The function needs to return the the total amount owed by multiplying the price by the quantity and then adding the extra fee.

function calculateTotalAmountDue(arr) {
  const price = arr[0];
  const quantity = arr[1];
  const fee = arr[2];
  return price * quanity + fee;

Using destructuring, I could make it more concise by:

function calculateSomething([ price, quantity, fee ]) {
  return price * quanity + fee;

The coolest ninja-style trick in destructuring is filtering an object:

const person = {
  name: 'snigo',
  age: 37,
  location: 'Barcelona',

const { age, ...noAge } = person;
console.log(noAge); // Because who stores age anyway??? :)
1 Like

Just as a counterpoint to what’s been said, it isn’t common to need to swap variables in JS (or to swap values in an array), but when it is needed, then this is imo the clearest way to do it. It’s not that it isn’t something useful in real life, it’s just not done that often. I know I’ve needed to do it a few times, it’s just that rare that I just can’t remember any specifics about why I needed to do it

As to why it’s the first example? I am only guessing here, but swapping variables is common in low-level algorithms of the kind you’d find in either low-level imperative © code or in CS textbooks. I feel like that’s what’s led to it being a common example of destructuring (people writing doc/blog posts/etc have copied people who copied people who thought it was an obvious example). See also basic Python, you’ll find loads of examples that are almost exactly the same if you dig around. It is probably meaningful if you’ve gone through a CS course and written out lots of sorting algorithms, where you have to swap variables a lot. The thought process in that case is likely to be more “ah I see, that’s seems simpler, I don’t have to use a temporary variable”, rather than “what the hell is this confusing thing”

It is pretty meaningless if you haven’t done anything that needs assigned variable values swapped. As you’ve found, it seems at first glanve to be pointless. It’s maybe the simplest possible example though, so bear that in mind