Event Loop & Call Stack in JavaScript - Exercise 1

The call stack tracks the functions JavaScript is currently executing. It follows last in, first out order.

function greet() { console.log('Hello'); }
function main() { greet(); }
main();
// main is pushed, then greet, then both are popped.

JavaScript has one main call stack, so it executes one piece of JavaScript at a time.

console.log('First');
console.log('Second');
// First finishes before Second starts.

The outer function pauses while the inner function runs, then continues after the inner call returns.

function outer() {
  console.log('outer start');
  inner();
  console.log('outer end');
}
function inner() { console.log('inner'); }
outer();

Each recursive call adds another frame to the stack. If the stack never empties, it exceeds its limit.

function repeat() {
  repeat();
}
// repeat(); // Maximum call stack size exceeded

No. Its callback waits until the current synchronous code finishes and the event loop can process the task.

console.log('start');
setTimeout(() => console.log('timer'), 0);
console.log('end');
// start, end, timer

It is a function ready to run after an asynchronous operation, such as a timer, completes.

setTimeout(function onTimerDone() {
  console.log('callback task');
}, 100);

It watches the call stack and queues, moving ready work to the stack only when the stack is empty.

console.log('sync work');
setTimeout(() => console.log('queued work'), 0);
// The event loop waits for sync work to finish.

Web APIs are browser-provided features such as timers, fetch, and DOM events that work outside the JavaScript call stack.

setTimeout(() => console.log('browser timer finished'), 500);
fetch('/data.json').then(() => console.log('response received'));