Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

251
Visualizações
Object destructuring in Javascript - trying to make sense

probably a bit of a silly question but I'm only a beginner and there's something I am trying to understand properly.

When we have code like this:

const { userName } = await getUserProfile({ userId });

What exactly is happening here? Are we destructuring userName out of the getUserProfile object to be able to access that property? And does userId mean that the getUserProfile function has a parameter that is an object that has a property userId?

Sorry, if this is too beginner of a question but would really appreciate it if anyone had the time to explain this to me please.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I'd say the function does something like this:

interface Options {
   userId: number;
}

interface ReturnItem {
  userName: string;
}

const getUserProfile = async (options: Options): Promise<ReturnItem> => {
  // make some request with the id
  const response = await axios.get(`/look/up/my/user/${options.userId}`);
  return response.data;
}

The destructuring is based off of the types defined in the function, so instead of getting an object back, you're just pulling the item out of the returned object as the types define that's what you can expect to receive.

Instead of doing the following:

const myId = 1;
const myResult = await getUserProfile({userId: myId});
console.log(myResult.userName);

you can do:

const userId = 1;
const {userName} = await getUserProfile({userId});
console.log(userName);

Another example:

const myReturnData = {
  userName: 'Bjork'
};

userName can now be accessed in the following ways:

console.log(myReturnData.userName);

or

const {userName} = myReturnData;
console.log(userName);

Destructuring is taking those values in your object and assigning them to variables.

A bit further..

const myReturnData = {
  userName: 'Bjork',
  coolnessFactor: 10000
};

const {userName, coolnessFactor} = myReturnData;
console.log('My User is: ', userName);
console.log('and my Coolnessfactor is: ', coolnessFactor);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda