Array deformation

3

I'm lost, where is the code logic?

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 const stretch, [Carol] = contacts, I could not understand?

    
asked by anonymous 13.06.2018 / 17:55

1 answer

7

This is called Assignment via destructuring . In this case, the code snippet declares the variable Carol, which will get the second position of the array that was passed, so the [, Carol] notation. This is similar to doing: const Carol = contatos[1] .

Remember 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 that 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];
    
13.06.2018 / 18:02