DEV Community

Opeyemi
Opeyemi

Posted on

Synchronous vs Asynchronous JavaScript!

JavaScript is a single threaaded, blocking programming language. However, how it handles operations can be categorized into synchronous and asynchronous execution.

Synchronous JavaScript

In synchronous JavaScript, operations are executed one at a time in a specific order. Each task waits for the previous one to complete before moving on to the next.

Key Characteristics of Synchronous JavaScript:

  • Blocks the execution of subsequent code until the current task completes.
  • Easier to understand but can cause delays if a task takes long time (e.g., heavy computation or network request).

Below is an example of Sychronous JavaScript:

In this example, each task runs sequentially.

Image description

Asynchronous JavaScript

In asynchronous JavaScript, tasks can be executed independently of the main thread. This allows the program to continue running other tasks whike waiting for longer operations (e.g file reads, APIs calls) to complete.

Key Characteristics of Asynchronous JavaScript:

  • Non-blocking: Other tasks can execute while waiting for an asynchronous task.
  • Used for tasks like fetching data, reading files, or handling timers.

Example of Asynchronous JavaScript:

Image description

In the example shown above, the task "third" doesn't wait for the last task to complete. The program continues execution without being blocked.

Asynchronous operations in JavaScript

a. callbacks:

A function passed as an argument to another function and executed later.

Image description

b. promise:

It is a function that represents the eventual completion or failure of an asynchronous operation and its resulting value. It acts as a substitute for a value that will be available in the future, helping you manage asynchronous code in a cleaner and more predictable way.

Image description

c. async/await:

Simplifies working with promises by writing asynchronous code tha t looks synchronous. This makes your code easier to read and understand.

Image description

Conclusion:

  • Synchronous code is simpler but blocks execution.

  • Asynchronous code allows for non-blocking operations, improving performance for tasks like network requests or timers. Understanding both is essential for effecient JavaScript programming.

Top comments (2)

Collapse
 
khaybee24 profile image
khaybee24

👌

Collapse
 
ayomide_olaniran_c1167216 profile image
Ayomide Olaniran

✌âœ