Skip to main content

Command Palette

Search for a command to run...

Understanding Asynchronous JavaScript: Why Your Array Is Empty?

Updated
1 min read
Understanding Asynchronous JavaScript: Why Your Array Is Empty?
S

I'm Shubham (@shubhamsinghbundela), I'm a Software Engineer, a Full-stack developer, a tech enthusiast, and a technical writer here on @Hashnode. I have a strong zeal to share my acquired knowledge and I am also willing to learn from others.

const worker = (delay) =>
  new Promise((resolve) =>
    setTimeout(() => resolve(`Finished ${delay}`), delay)
  );

async function run() {
  let results = [];
  let items = [2, 10, 2];

  for (let i = 0; i < items.length; i++) {
    const data = await worker(items[i]);
    results.push(data);
  }

  console.log("Final results:", results);
}

run();

The Confusion

  • Inside the callback → results contains data

  • Outside the callback → results is still []


The Real Reason: Asynchronous Execution

The key lies in this line:

setTimeout(...)

setTimeout is asynchronous.

That means:

  • The for loop runs immediately.

  • The callback runs later.

  • JavaScript does NOT wait for it.


How JavaScript Actually Works

JavaScript:

  • Is single-threaded

  • Uses the Event Loop

  • Sends setTimeout to Web APIs

  • Pushes callback to Callback Queue

  • Executes it when Call Stack is empty

So your loop finishes before any timeout completes.


Final Takeaway

If you remember just one thing from this blog:

The loop runs synchronously.
setTimeout runs asynchronously.
JavaScript does NOT wait unless you tell it to.

More from this blog

Shubham Tech. Blog's

55 posts

Problem Solver | Currently Working As a Full Stack Developer, Community Leader At @Dev_Matrix | Previously Contributor at @RealDevSquad, @TeamShiksha