Destructuring is one of the most powerful features added to the language in ES2015, a feature that makes things easier and our code more readable.
Destructuring gives us a way to extract data from objects or arrays and assign them to variables.
Arrays
Imagine we have an array with three elements:
const array = ['pato', 'ganzo', 'pollo'];
If in ES5 we wanted to assign these values to variables, we’d have to do it like this:
var primer = array[0];
var segundo = array[1];
var tercero = array[2];
But with destructuring in ES2015, we’d do it like this:
const [a,b,c] = array;
// a = 'pato'
// b = 'ganzo'
// c = 'pollo
Pretty cool! Much simpler and more readable. But what if we wanted to skip an element? We could do the assignment like this:
const [a,,c] = array;
// a = 'pato'
// c = 'pollo'
There’s a really useful use case here: imagine you have two variables and you want to swap their values. In ES5, we’d need to create a temporary variable for this, but with destructuring all you’d need is:
let x = 2;
let y = 5;
[x,y] = [y,x];
// x = 5
// y = 2
Much more useful and readable, right?
Think it could work with arrays returned by a function? Give it a try and let me know!
Code for the examples at jsbin.com
Objects
Just like with arrays, we can also use destructuring features with objects. Imagine an object like this:
const objeto = {
a: 'casa',
b: 'apartamento'
};
How would we assign the properties of objeto to variables in ES5?
var a = objeto.a;
var b = objeto.b;
With destructuring in ES2015, we’d do it like this:
const {a,b} = objeto;
//a = 'casa'
//b = 'apartamento'
If we wanted to assign the object’s properties to variables with different names, we’d do it like this:
const {a:uno,b:dos} = objeto;
//uno = 'casa'
//dos = 'apartamento'
Now that we know this, let’s do something useful.
Default Values in Functions
If we have a function that receives an object as a parameter and we wanted to set default values in ES5, we’d do it like this:
function hablar(datos){
datos = datos === undefined ? {} : opciones;
nombre = datos.nombre === undefined ? 'Yeison' : opciones.nombre;
pais = datos.pais === undefined ? 'colombia' : opciones.pais;
console.log('Hola soy ' + nombre + ' y vivo en ' + pais);
}
hablar();
Doesn’t look great, right? But with destructuring we could do something like this:
function hablar({nombre = 'yeison', pais ='colombia'} = {}){
console.log(`Hola soy ${nombre} y vivo en ${pais}`);
}
//Hola soy yeison y vivo en colombia
It’s much more readable! And if we wanted to print different values, we’d simply pass an object with the property values we want as the function parameter:
hablar({
nombre: 'felipe',
pais: 'argentina'
});
//Hola soy felipe y vivo en argentina
Code for object examples at jsbin.com
Handling Nested Objects
const yeison = {
id: 27,
user: 'yeion7',
datos: {
nombre: 'Yeison',
apellido: 'Daza',
edad: '22'
}
}
function decirNombre(
{
user: nickName,
datos:{ nombre: primerNombre }
}) {
console.log(`El usuario ${nickName} se llama ${primerNombre}`);
}
decirNombre(yeison);
Nested object — See the example code at jsbin.com
Think you could use this in loops? Give it a try and let me know how you do it!