Doubt when executing the function

Asked

Viewed 24 times

0

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; 
function mostraNumero({numero}){  // aqui mora a dúvida
console.log(numero)
}
mostraNumero(Carol);

When executing the code, when calling the function mostraNumero():

When invoked mostraNumero(Carol), soon (Carol) ----> ({numero}) becomes the parameter. Summarizing:

Carol = {
        nome: 'Carolina Moya',
        numero: '1234-6789'
    }

As just writing {numero} has already been able to access the property and value, after (numero) accesses the direct value. I thought I had to use the dot notation (.) to access a property. Someone can clarify for me?

1 answer

0


Face this concept is called De-structuring, it kind of consists of you creating a variable with the name of the object attribute passing as value the object...

Example:

var obj = {
    nome: 'joao',
    idade: 23
};

var { idade } = obj;

The age value will be 23, because you took the age value of the object obj, it would be the same thing you do:

var idade = obj.idade;

In case you did:

var { idade, nome } = obj;

The age value will also be 23 and the name value will be john, but in separate variables within the properties of an object.

In your case there in the function you did the same thing but with array, Carol is an object, and at the time of the function { numero } would be the object number Carol.

Browser other questions tagged

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