Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

381
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!