# [How to Use Object Destructuring in JavaScript](https://dmitripavlutin.com/javascript-object-destructuring/)
Destructuring assignment is special syntax introduced in ES6, for neatly assigning values taken directly from an array or object.
Put another way, it's a way of giving a label to each item off the array or object)
#### Destructuring Objects
```js
// ES5
const user = { name: 'John Doe', age: 34 };
const name = user.name; // console.log(name) //➞ 'John Doe'
const age = user.age; // console.log(age) //➞ 34
```
```js
// Destructuring (ES6)
const user = { name: 'John Doe', age: 34 };
// get the name key from the user object and store it as its own variable (with the value being the value associated with the name key)
const { name } = user;
console.log(name); //➞ 'John Doe'
```
Destructuring allows you to assign a new variable name when extracting values. You can do this by putting the new name after a colon when assigning the value.
```js
const user = { name: 'John Doe', age: 34 };
// get the age key from the user object and store it as its own variable (with the value being the value associated with the name key)
const { age: userAge } = user;
console.log(userAge); //➞ 34
```
Destructuring values from nested objects:
```js
// object
const user = {
johnDoe: {
age: 34,
email: '
[email protected]'
}
};
// assigning to variables keeping the same name
const { johnDoe: { age, email }} = user;
const {johnDoe} = user;
console.log(johnDoe) //➞ {age: 34, email: '
[email protected]'};
console.log(age); //➞ 34
console.log(email); //➞ '
[email protected]'
// assigning to variables with different names
const { johnDoe: { age: userAge, email: userEmail }} = user;
console.log(userAge); //➞ 34
console.log(userEmail); //➞ '
[email protected]'
```
#### Destructuring arrays
ES6 makes destructuring arrays as easy as destructuring objects.
One key difference between the spread operator and array destructuring is that the spread operator unpacks all contents of an array into a comma-separated list. Consequently, you cannot pick or choose which elements you want to assign to variables.
Destructuring an array lets us do exactly that:
```js
const [a, b] = [1, 2, 3, 4, 5, 6];
console.log(a, b); //➞ 1 2
```
We can also access the value at any index in an array with destructuring by using commas to reach the desired index:
```js
const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c); //➞ 1 2 5
```
#### More Examples:
```JS
const req = {
query: {
id: 'abc'
},
name: 'larry'
}
const { id } = req.query
console.log(id); //➞ 'abc'
const params = [ id ];
console.log(params); //➞ ['abc']
const { query } = req;
console.log(query); //➞ {id: 'abc'}
```
___
**Tags**: #es6 #destructuring #to-be-completed