Doubt in attribution via destructuring-Javascript

I could not understand the following code:

//Esse array vai modificar o DOM com o seu conteúdo
const elementos = [             
    { tag: 'p', texto: 'Frase 1' }, // indice 0
    { tag: 'div', texto: 'Frase 2' }, // indice 1
    { tag: 'section', texto: 'Frase 3' }, // indice 2
    { tag: 'footer', texto: 'Frase 4' } // indice 3
];

const container = document.querySelector('.container');
const div = document.createElement('div');

for (let i = 0; i < elementos.length; i++) {
    const { tag, texto } = elementos[i]; 
    const elemento = document.createElement(tag);
    const noTexto = document.createTextNode(texto);
    elemento.appendChild(noTexto);
    div.appendChild(elemento);
    console.log(elementos[i]);
}
container.appendChild(div);

The code is working normally, in case, my doubt is: why at the time of assigning, it is not necessary to put the brackets? Ex: [{tag, texto}] = elementos[i];

Author: ℛɑƒæĿᴿᴹᴿ, 2020-03-11

2 answers

If you did what you would like, it would try to look for a 1 position in the vector that is doing the destructure, but since it is in a for and has already selected the position, the only way to work out this syntax would be in a case like this:

const elementos = [             
    { tag: 'p', texto: 'Frase 1' },
    { tag: 'div', texto: 'Frase 2' },
    { tag: 'section', texto: 'Frase 3' },
    { tag: 'footer', texto: 'Frase 4' }
]
const [{ tag, texto }] = elementos

Then it would just work out the way you wanted in this case:

const elementos = [
    [{ tag: 'p', texto: 'Frase 1' }],
    [{ tag: 'div', texto: 'Frase 2' }],
    [{ tag: 'section', texto: 'Frase 3' }],
    [{ tag: 'footer', texto: 'Frase 4' }]
]
const [{ tag, texto }] = elementos[0]

I.e. I would need to put another vector inside the vector, thus becoming an array. An observation if you were using TypeScript would have given an error that to solve you could use // @ts-ignore in the previous line or use the following syntax:

const elementos = [             
    { tag: 'p', texto: 'Frase 1' },
    { tag: 'div', texto: 'Frase 2' },
    { tag: 'section', texto: 'Frase 3' },
    { tag: 'footer', texto: 'Frase 4' }
]
// forma longa
const [indice1] = elementos
const { tag, texto } = indice1
// forma curta (foi a forma como foi feita na pergunta)
const { tag, texto } = elementos[0]
 1
Author: greguintow, 2020-03-12 00:22:54

Basically, what vc is doing is removing the internal properties of the array, unstructuring the values present inside the array into objects.

Because it is inside a for, it is necessary to reference the index of the item for the values to be assigned correctly.

 0
Author: Diogo Lima Franco, 2020-03-12 01:07:57