Destructuring
Destructuring lets you "unpack" values from arrays and objects into independent variables in a concise way.
Destructuring arrays
const coordinates = [10, 20];
const [x, y] = coordinates;
console.log(x, y); // 10 20
They are assigned by position. You can skip elements with commas:
const [first, , third] = ["a", "b", "c"];
console.log(first, third); // "a" "c"
Destructuring objects
Here they are assigned by property name:
const person = { name: "Ana", age: 30 };
const { name, age } = person;
console.log(name, age); // "Ana" 30
Renaming and default values
const { name: n, country = "Spain" } = person;
console.log(n); // "Ana"
console.log(country); // "Spain" (didn't exist, uses the default value)
Destructuring is very common when receiving parameters in functions:
function greet({ name }) {
return "Hello, " + name;
}
greet({ name: "Luis" }); // "Hello, Luis"
Examples
Swap variables with destructuring
let a = 1;
let b = 2;
[a, b] = [b, a]; // modern trick to swap
console.log(a, b); // 2 1