• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

315
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 3 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 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error