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.
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.
const obj = { a: 1, b: 2 };
const { a, b } = obj;
// is equivalent to:
// const a = obj.a;
// const b = obj.b;
In React, you can use object destructuring to extract props from a component.
const MyComponent = ({ name, age }) => {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
};
Example 1:
function App() {
const [num, setNum] = useState(0);
}
Example 2:
function App() {
const [state, setState] = useState({
name: "John",
age: 32,
});
const { name, age } = state;
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
function App() {
const [state, setState] = useState({
name: "John",
age: 32,
});
const { name, age } = state;
useEffect(() => {
console.log(name);
}, [name]);
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
Basic variable assignment.
const foo = ['one', 'two', 'three'];
console.log(red); // "one"
console.log(green); // "two"
console.log(blue); // "three"
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.
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
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.
function f() {
return [1, 2];
}
const [a, b] = f();
console.log(a); // 1
console.log(b); // 2
You can ignore some returned values by using commas.
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.
function f() {
return [1, 2, 3];
}
const [,,] = f();
You can assign the remainder of an array to a variable using the rest syntax.
const [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
const o = { p: 42, q: true };
const { p, q } = o;
console.log(p); // 42
console.log(q); // true
A property can be unpacked from an object and assigned to a variable with a different name than the object property.
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.
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.
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.
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"
NOTE: This is awesome when you have an array of objects
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"
You can destructure objects and arrays as arguments in function calls.
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
});
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
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"
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.