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

384
Visualizações
Refactoring JavaScript, shortening variable declaration

I have the following code that works as expected:

(async () => {
  const first = document.getElementById("first"), second = document.getElementById("second");
  try {
    first.innerHTML = await (await fetch('https://myAPI.com/1')).text();
    second.innerHTML = await (await fetch('https://myAPI.com/2')).text();
  } catch {
    first.innerHTML = 'Error';
    second.innerHTML = 'Error';
  }
})();

But I am curious whether there is a way to shorten the declaration of my variables, something like this (which doesn't work):

(async () => {
  const [first, second] = document.getElementById("[first, second]");
  try {
    first.innerHTML = await (await fetch('https://myAPI.com/1')).text();
    second.innerHTML = await (await fetch('https://myAPI.com/2')).text();
  } catch {
    first.innerHTML = 'Error';
    second.innerHTML = 'Error';
  }
})();

Just curious as to whether I can get rid of that second appearance of 'document.getElementById' to make the line more compact.

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

0

The most concise way to do it is by using the following:

const [first, second] = document.querySelectorAll("#first, #second");
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