Destructuring is a feature of several programming languages that allows decomposing complex data structures (such as tuples, collections, and objects), and assigning them to individual variables.
In summary, many languages allow composing variables into collections or groupings. It is common that at some point we want to “undo” this composition and create individual variables for each of the members.
Destructuring allows us to perform this operation concisely. Let’s see it with an example. Suppose we have a grouping person
, which contains name
and age
.
// composition
const person = { name: "Luis", age: 30 };
// traditional decomposition
const name = person.name;
const age = person.age;
// with destructuring
const { name, age } = person;
Destructuring person
allows us to create two new variables name
and age
, in a simpler way than with “traditional” variable assignment.
Example of destructuring in different languages
Not all languages that incorporate destructuring allow destructuring all types. However, it is a trend that they increasingly expand this functionality because it is sometimes very convenient.
Let’s see how different languages incorporate the concept of destructuring to a greater or lesser extent.
In C#, tuples and records can be destructured directly into individual variables.
var tuple = (1, "Hello", 3.5);
var (integer, greeting, number) = tuple;
In C++, it also has destructuring functions for structs and tuples.
struct Person {
std::string name;
int age;
};
Person person = {"John", 30};
auto [name, age] = person;
In JavaScript, it is the absolute king of destructuring, allowing the destructuring of objects and collections.
const person = { name: "Luis", age: 30 };
const { name, age } = person;
const numbers = [1, 2, 3];
const [first, second, third] = numbers;
In Python, it also incorporates very powerful destructuring functions for tuples and even collections.
tuple = (1, "Hello", 3.5)
number, greeting, decimal = tuple