Destructuring of Arrays

Asked

Viewed 137 times

4

I’m lost, where is the logic of the code?

const contatos = [
    {
        nome: 'Alex Júnior',
        numero: '1234-5678'
    },
    {
        nome: 'Carolina Moya',
        numero: '1234-6789'
    },
    {
        nome: 'Fernando Jorge',
        numero: '12345-5567'
    }
];
const [, Carol] = contatos; // Não entendi esse trecho
function mostraNumero({numero}){
    console.log(numero)
}
mostraNumero(Carol);

What is the purpose of the excerpt const [, Carol] = contacts, I could not understand?

1 answer

7


It’s called Allocation via de-structuring. In this case, the code snippet declares the Carol variable, which will receive the second position of the array that was passed, so the notation [, Carol]. This is similar to doing: const Carol = contatos[1].

Note that this is an addition to ES6, so it may not be available in all browsers.

EDIT: Making one more addition, to make it even clearer. In the example you put, we could also do:

const contatos = [
    {
        nome: 'Alex Júnior',
        numero: '1234-5678'
    },
    {
        nome: 'Carolina Moya',
        numero: '1234-6789'
    },
    {
        nome: 'Fernando Jorge',
        numero: '12345-5567'
    }
];
const [Alex , Carol] = contatos; // Não entendi esse trecho
function mostraNumero({numero}){
    console.log(numero)
}
mostraNumero(Carol);
mostraNumero(Alex);

That would be equivalent to doing:

const Alex = contatos[0];
const Carol = contatos[1];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.