DEV Community

swetha palani
swetha palani

Posted on

Synchronous JavaScript

JavaScript is one of the most popular programming languages used for web development. By default, JavaScript is synchronous and single-threaded, which means it executes code line by line. To understand how JavaScript works, you must first learn about its synchronous nature.

What is Synchronous JavaScript?

The word synchronous means tasks are performed one after another in sequence.

  • Only one statement executes at a time.
  • The next line of code waits until the current one finishes.
  • This is because JavaScript has a single execution thread.

Example: Imagine standing in a queue at a billing counter. Each customer is served one by one.

Example of Synchronous Execution

console.log("Step 1");
console.log("Step 2");
console.log("Step 3");
Enter fullscreen mode Exit fullscreen mode

Output:

Step 1
Step 2
Step 3
Enter fullscreen mode Exit fullscreen mode

📌 Example of Blocking in Synchronous Code

console.log("Start");

for (let i = 0; i < 1000000000; i++) {

}

console.log("End");
Enter fullscreen mode Exit fullscreen mode

Output:

Start
End
Enter fullscreen mode Exit fullscreen mode

➡ The loop takes time, so the program is blocked until the loop finishes.
➡ This means the page or program can freeze if a heavy synchronous task runs.

Key Characteristics of Synchronous JavaScript

  1. Single-threaded – Executes one task at a time.
  2. Blocking – Long tasks stop other code from running.
  3. Sequential – Code runs from top to bottom in order.
  4. Predictable – Output is easy to understand since it follows strict order.

Advantages of Synchronous JavaScript

  • Easy to read and understand.

  • Good for simple tasks.

  • Predictable flow of execution.

Disadvantages of Synchronous JavaScript

  • Long tasks block the entire program.

  • Not suitable for network requests or heavy operations.

  • User experience may suffer (app freezes, UI stuck).

When to Use Synchronous JavaScript?

  • For small tasks like calculations.
  • For simple scripts where performance is not a big issue.
  • For learning basics of execution flow.

Conclusion

JavaScript is synchronous by default, which means it runs one line at a time in order. While this makes it simple and predictable, it can also cause blocking issues in long-running tasks.

Top comments (0)