Destructuring is a feature in 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 on some occasions we want to “undo” this composition and create individual variables for each of the members.
Destructuring allows performing this operation concisely. Let’s see it with an example. Suppose we have a person grouping that 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. But it is a trend that they increasingly expand this functionality because sometimes it is 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;
C++ also has destructuring functions for structs and tuples.
struct Person {
std::string name;
int age;
};
Person person = {"John", 30};
auto [name, age] = person;
JavaScript is the absolute king of destructuring, allowing 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;
Python also incorporates very powerful functions for destructuring tuples and even collections.
tuple = (1, "Hello", 3.5)
number, greeting, decimal = tuple
