# Destructuring in JavaScript

### What destructuring means

Destructuring simply means to destructure or breakdown or split something, an array or object to get its contents.

Destructuring has various use cases like, destructuring array to add elements, or destructuring to assign default values in function arguments.

### Destructuring Arrays

```javascript
let arr = ["Kushagra", "Trivedi"]

// destructuring assignment
// sets firstName = arr[0]
// and surname = arr[1]
let [firstName, surname] = arr;

alert(firstName); // Kushahgra
alert(surname);  // Trivedi
```

We can also do:

```javascript
let [firstname, lastname] = "Kushagra Trivedi".split(" ");
alert(firstname); // Kushagra
alert(lastname); // Trivedi
```

Actually, we can use it with any iterable, not only arrays:

```javascript
let [a, b, c] = "abc"; // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3]);
```

That works, because internally a destructuring assignment works by iterating over the right value. It’s a kind of syntax sugar for calling `for..of` over the value to the right of `=` and assigning the values.

* * *

We can use any “assignables” on the left side.

For instance, an object property:

```javascript
let user = {};
[user.name, user.surname] = "John Smith".split(' ');

alert(user.name); // John
alert(user.surname); // Smith
```

* * *

In the previous chapter, we saw the [Object.entries(obj)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) method.

We can use it with destructuring to loop over the keys-and-values of an object:

```javascript
let user = {
  name: "John",
  age: 30
};

// loop over the keys-and-values
for (let [key, value] of Object.entries(user)) {
  alert(`${key}:${value}`); // name:John, then age:30
}

//The similar code for a Map is simpler, as it’s iterable:

let user = new Map();
user.set("name", "John");
user.set("age", "30");

// Map iterates as [key, value] pairs, very convenient for destructuring
for (let [key, value] of user) {
  alert(`${key}:${value}`); // name:John, then age:30
}
```

* * *

There’s a well-known trick for swapping values of two variables using a destructuring assignment:

```javascript
let guest = "Jane";
let admin = "Pete";

// Let's swap the values: make guest=Pete, admin=Jane
[guest, admin] = [admin, guest];

alert(`${guest} ${admin}`); // Pete Jane (successfully swapped!)
```

Here we create a temporary array of two variables and immediately destructure it in swapped order.

We can swap more than two variables this way.

* * *

If the array is longer than the items on the left, then

```javascript
let [first, second] = ['one', 'two', 'three', 'four'];
alert(first);     // one
alert(second);   // two
// Further items aren't assigned anywhere
```

So we use `'...'`

```javascript
let [first, second, ...third] = ['one', 'two', 'three', 'four']
console.log(third) // ['three', 'four']
```

Now this is how we assign default values

```javascript
let [name = "Kushagra", surname = "Trivedi"] = ["Julius"];

alert(name);    // Julius (from array)
alert(surname); // Trivedi (default used)
```

We can also provide functions as default values. They are evaluated only if the value is not provided.

For instance, here we use the `prompt` function for two defaults:

```javascript
// runs only prompt for surname
let [name = prompt('name?'), surname = prompt('surname?')] = ["Julius"];

alert(name);    // Julius (from array)
alert(surname); // whatever prompt gets
```

Please note: the `prompt` will run only for the missing value (`surname`).

### Object Destructuring

Now just as we do with arrays, we can also destructure objects

```javascript
const {firstname, lastname} = {firstname : "kush", lastname : 'trivedi'}
console.log(firstname);   // kush
console.log(lastname);   // trivedi
```

order does not matter here

```javascript
const {lastname, firstname} = {firstname : "kush", lastname : 'trivedi'}
console.log(firstname);   // kush
console.log(lastname);   // trivedi
```

* * *

we can set default values using `"="`, like this:

```javascript
let options = {
  title: "Menu"
};

let {width = 100, height = 200, title} = options;

alert(title);  // Menu
alert(width);  // 100
alert(height); // 200
```

Here also default values can be expressions

```javascript
let options = {
  title: "Menu"
};

let {width = prompt("width?"), title = prompt("title?")} = options;

alert(title);  // Menu
alert(width);  // (whatever the result of prompt is)
```

* * *

Just like we did in Arrays, we can use '`...'` to destructure objects

```javascript
let options = {
  title : "Menu",
  height : 200,
  width : 100
};

// title = property named title
// rest = object with the rest of properties
let {title, ...rest} = options;

// now title="Menu", rest={height: 200, width: 100}
alert(rest.height);  // 200
```

Nested destructuring is also possible

```javascript
let obj = {
first : "kush",
last : "trivedi",
age : { years : 21, months : 3 },
}

let destobj = {first, last, age : { years, months } } = obj;
console.log(years);   // 21
```

* * *

When a function has many parameters, and many of these parameters are optional, i.e, are have default values, it becomes difficult to remember the order of parameters.

Destructuring comes to the rescue!

We can pass parameters as an object, and the function immediately destructurizes them into variables:

```javascript
let obj = {
  title : "My menu",
  items : ["Item1", "Item2"]
};

function sample({title = "Untitled", width = 200, height = 100, items = []}) {
  // title, items – taken from obj,
  // width, height – defaults used
  alert( `${title} ${width} ${height}` ); // My Menu 200 100
  alert( items ); // Item1, Item2
}

sample(obj);
```

That's all, hope you enjoyed it.

### Sources

[Destructuring assignment](https://javascript.info/destructuring-assignment)
