JavaScript

JavaScript Closures and the Event Loop, Explained Simply

6 min read R Square IT Support TeamSample article

Two of the most asked JavaScript interview topics, explained with small examples you can reproduce on a whiteboard.

Closures

A closure is a function that remembers the variables from the scope where it was created, even after that outer function has finished running.

javascript
function createCounter() {
  let count = 0;
  return () => ++count;
}

const next = createCounter();
next(); // 1
next(); // 2 — count is preserved by the closure

Closures power data privacy, function factories, memoization and many callback patterns.

The event loop

JavaScript runs on a single thread. Synchronous code runs on the call stack first. Async callbacks wait in queues: the microtask queue (promises) is emptied before the next macrotask (setTimeout, I/O) runs.

javascript
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');

// Output: A, D, C, B

Why is C printed before B?

Promise callbacks are microtasks, and all microtasks run before the next macrotask such as a setTimeout callback.

  • JavaScript
  • Closures
  • Event Loop

This is a sample article published as a starter resource. Verify technical details against official documentation for the versions you use.

Prepare. Perform. Progress.

Want personal guidance on this topic?

Our team can help you prepare, solve doubts and practise interviews around what you are learning.

Chat with us