DEV Community

Raja B
Raja B

Posted on

JavaScript Synchronous and Asynchronous

Definition:

Type Simple Meaning
Synchronous Code runs one after another - each task waits for previous to finish
Asynchronous Code runs independently - tasks don't block other code while waiting
  • Synchronous: "Wait for me to finish before you start" [blocking]
  • Asynchronous: "You start while I wait - call me back when done" [non-blocking]

1. Synchronous JavaScript (Normal/Default)

How it works:

  • Code executes line by line in order

  • Each statement waits for previous one to complete

  • Blocks execution until task finishes

Example:

sync

Characteristics:

Feature Description
Execution Fixed sequence
Blocking Yes - blocks other code
Complexity Simple, easy to understand
Speed Slower for time-consuming tasks
Best for Simple, sequential tasks

2. Asynchronous JavaScript (Modern)

How it works:

  • Task starts in background

  • Code continues without waiting

  • Gets callback when task completes

Example (Non-blocking):

asyn

Characteristics:

Feature Description
Execution Tasks run independently
Blocking No - non-blocking
Complexity More complex (callbacks, promises)
Speed Faster for slow operations
Best for API calls, timers, file operations

Asynchronous Patterns in JavaScript

1. Callbacks (Old way)

call

Callback: Function that runs later - "calls you back" when done

2. Promises (Modern way)

Promise: Object representing async operation completion

  • States: pending → fulfilled or rejected

3. async/await (Best way - clean)

  • async: Function returns Promise

  • await: Waits for Promise (but doesn't block!)


Important Points

  1. JavaScript is Synchronous by Default

sycn

2.JavaScript is Single-Threaded

  • Only 1 Call Stack
  • Executes one thing at a time

3.But Async Makes It Concurrent

  • Event Loop + Web APIs enable multiple tasks

4.Common Async Operations

Operation Async Method
Timer setTimeout()
API Call fetch()
File Read readFile()
Events addEventListener()

Summary

Question Answer
What is sync? Code runs one after another
What is async? Code runs independently, non-blocking
Which blocks? Sync blocks, async doesn't
Default in JS? Synchronous
How async works? Event Loop + Web APIs + Callback Queue
Best async pattern? async/await (clean code)
Reference:

Top comments (0)