# Object Destructuring
The object and array literal expressions provide an easy way to create ad hoc packages of data.
`const x = [1, 2, 3, 4, 5];`
The destructuring assignment uses similar syntax, but on the left-hand side of the assignment to define what values to unpack from the sourced variable.
```js
const x = [1, 2, 3, 4, 5];
const [y, z] = x;
console.log(y); // 1
console.log(z); // 2
```
Similarly, you can destructure objects on the left-hand side of the assignment.
```js
const obj = { a: 1, b: 2 };
const { a, b } = obj;
// is equivalent to:
// const a = obj.a;
// const b = obj.b;
```
## Object Destructuring in React
In React, you can use object destructuring to extract props from a component.
```js
const MyComponent = ({ name, age }) => {
return (
);
};
```
## Object Destructuring in React useState
Example 1:
```js
function App() {
const [num, setNum] = useState(0);
}
```
Example 2:
```js
function App() {
const [state, setState] = useState({
name: "John",
age: 32,
});
const { name, age } = state;
return (
);
}
```
## Object Destructuring in React useEffect
```js
function App() {
const [state, setState] = useState({
name: "John",
age: 32,
});
const { name, age } = state;
useEffect(() => {
console.log(name);
}, [name]);
return (
);
}
```
## More examples
### Array destructuring
Basic variable assignment.
```js
const foo = ['one', 'two', 'three'];
console.log(red); // "one"
console.log(green); // "two"
console.log(blue); // "three"
```
#### Destructuring with more elements than the source
In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N, only the first N variables are assigned values. The values of the remaining variables will be undefined.
```js
const foo = ['one', 'two', 'three'];
const [red, green, blue, yellow, purple] = foo;
console.log(red); // "one"
console.log(green); // "two"
console.log(blue); // "three"
console.log(yellow); // undefined
console.log(purple); // undefined
```
#### Parsing an array returned from a function
It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.
In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.
```js
function f() {
return [1, 2];
}
const [a, b] = f();
console.log(a); // 1
console.log(b); // 2
```
#### Ignoring some returned values
You can ignore some returned values by using commas.
```js
function f() {
return [1, 2, 3];
}
const [a, , b] = f();
console.log(a); // 1
console.log(b); // 3
const [c] = f();
console.log(c); // 1
```
You can also ignore all returned values by using commas.
```js
function f() {
return [1, 2, 3];
}
const [,,] = f();
```
You can assign the remainder of an array to a variable using the rest syntax.
```js
const [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
```
### Object destructuring
#### Basic assignment
```js
const o = { p: 42, q: true };
const { p, q } = o;
console.log(p); // 42
console.log(q); // true
```
#### Assigning to new variable names
A property can be unpacked from an object and assigned to a variable with a different name than the object property.
```js
const o = { p: 42, q: true };
const { p: foo, q: bar } = o;
console.log(foo); // 42
console.log(bar); // true
```
Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo.
**This is especially helpful when dealing with name collisions, or in working with names that are not valid variable names.**
#### Assigning to new variable names and providing default values
A property can be both
- Unpacked from an object and assigned to a variable with a different name.
- Assigned a default value in case the unpacked value is undefined.
```js
const { a: aa = 10, b: bb = 5 } = { a: 3 };
console.log(aa); // 3
console.log(bb); // 5
```
**NOTE: You can also unpack properties from nested objects.**
```js
const metadata = {
title: 'Scratchpad',
translations: [
{
locale: 'de',
localization_tags: [],
last_edit: '2014-04-14T08:43:37',
url: '/de/docs/Tools/Scratchpad',
title: 'JavaScript-Umgebung'
}
],
url: '/en-US/docs/Tools/Scratchpad'
};
let {
title: englishTitle, // rename
translations: [
{
title: localeTitle, // rename
},
],
} = metadata;
console.log(englishTitle); // "Scratchpad"
console.log(localeTitle); // "JavaScript-Umgebung"
```
### Destructuring in Loops
#### Array destructuring in For Loops
**NOTE: This is awesome when you have an array of objects**
```js
const people = [
{
name: 'Mike Smith',
family: {
mother: 'Jane Smith',
father: 'Harry Smith',
sister: 'Samantha Smith'
},
age: 35
},
{
name: 'Tom Jones',
family: {
mother: 'Norah Jones',
father: 'Richard Jones',
brother: 'Howard Jones'
},
age: 25
}
];
for (const { name: n, family: { father: f } } of people) {
console.log('Name: ' + n + ', Father: ' + f);
}
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"
```
### Destructuring in Functions
You can destructure objects and arrays as arguments in function calls.
```js
function drawES2015Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
console.log(size, cords, radius);
// do some chart drawing
}
drawES2015Chart({
cords: { x: 18, y: 30 },
radius: 30
});
```
### Swapping variables
```js
let a = 1;
let b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
```
**Note: This is a common interview question**
### Desctructuring in Regular Expressions
```js
const url = 'https://developer.mozilla.org/en-US/Web/JavaScript';
const parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
const [, protocol, fullhost, fullpath] = parsedURL;
console.log(protocol); // "https"
console.log(fullhost); // "developer.mozilla.org"
console.log(fullpath); // "en-US/Web/JavaScript"
```
### Destructuring with Dynamic Properties
```js
const key = 'z';
const { [key]: foo } = { z: 'bar' };
console.log(foo); // "bar"
```
**Note: Here we're using a computed properties in destructuring just like you can in object literals. By wrapping the property value in brackets like `[key]` it now takes a variable as it's value instead of a static name. In other words, it's computed at runtime. You follow it with a colon `[key]: foo` to provide it with a static variable name to use in your code.**
For more information, see [Destructuring on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).