JavaScript can run code in two different ways: synchronous and asynchronous.
In synchronous code, each task waits for the previous one to finish. This can slow down applications when a task takes a long time.
In asynchronous code, long-running tasks run in the background, allowing the rest of the program to continue. This makes applications faster and more responsive.
Difference Between Synchronous and Asynchronous
Synchronous:
- Tasks run one after another
- Each task waits for the previous task
- Can make apps slow
Asynchronous:
- Long tasks run in background
- App stays responsive
- Best for loading data and handling user actions
Modern JavaScript relies heavily on asynchronous programming.
This code runs line by line. Each message is printed in order.
This is an example of synchronous execution.
Here, the setTimeout function runs after 2 seconds.
The program does not wait — it continues running other code.
These examples show how asynchronous code allows JavaScript to handle long tasks without freezing the application.
By understanding synchronous and asynchronous behavior, students gain the foundation needed to work with APIs, servers, and real-world JavaScript applications.