Language: EN

programacion-destructuracion

What is and how to use destructuring

Destructuring is a feature of several programming languages that allows you to break down complex data structures such as tuples, collections, and objects, and assign them to individual variables.

In short, many languages allow you to compose 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 you to perform this operation concisely. Let’s see an example. Suppose we have a grouping person, which contains name and age.

Destructuring person allows us to create two new variables name and age, more easily than with “traditional” variable assignment.

// composition
const person = { name: "Juan", age: 30 };

// traditional `decomposition`
const name = person.name;
const age = person.age;

// with destructuring
const { name, age } = person;

Example of destructuring in different languages

Not all languages that incorporate destructuring allow destructuring all types. But it is a trend that increasingly expands 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;

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 destructuring of objects and collections.

const person = { name: "Juan", age: 30 };
const { name, age } = person;

const numbers = [1, 2, 3];
const [first, second, third] = numbers;

In Python it also incorporates very powerful functions for destructuring tuples and even collections.

tuple = (1, "Hello", 3.5)
number, greeting, decimal = tuple