25 min·intermediate

Lesson 1

Sync vs async

Build a practical mental model for sync vs async and use it in working JavaScript.

By the end, you will be able to…

  • Explain sync vs async in your own words
  • Use sync vs async in a small program
  • Recognize and debug a common failure mode

Build the mental model

Synchronous code runs immediately, in order, on the call stack. Asynchronous work (timers, network requests) is handed off and its callback only runs after the current synchronous code finishes completely.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: 1 3 2

Why this matters

This single ordering fact explains almost every 'why did this run in the wrong order' confusion beginners have with timers and network calls.

Real-world example

A page that shows a loading spinner immediately, then updates once a fetch resolves later, is sync-then-async in exactly this order.

Common mistakes

  • Expecting a setTimeout callback to run before the synchronous code below it
  • Assuming async code runs 'in parallel' on another CPU core (JavaScript is single-threaded)
  • Not realizing setTimeout(fn, 0) still waits for the current call stack to empty

Try it yourself

Challenge

Predict and verify the logging order of three statements mixing sync code and a timer.

Practice

Knowledge check

In what order do these log: console.log('a'); setTimeout(() => console.log('b'), 0); console.log('c');?

Summary

Synchronous code always finishes first; asynchronous callbacks run only after the call stack is empty.