Explain the difference between synchronous and asynchronous functions in JavaScript

Answer

JavaScript functions can operate in either synchronous or asynchronous modes, depending on how they execute and handle tasks.


Synchronous Functions

Definition Synchronous functions execute one at a time, in the order they appear. The program waits for a function to complete before moving to the next one.

Characteristics

Example

console.log('Start');
console.log('Middle');
console.log('End');

Output:

Start
Middle
End

In the above example, each console.log runs sequentially.


Asynchronous Functions

Definition Asynchronous functions allow tasks to run independently of the main thread. The program does not wait for the task to complete and continues execution.

Characteristics

console.log('Start');
setTimeout(() => {
  console.log('Middle');
}, 1000);
console.log('End');

Output:

Start
End
Middle

Here, the setTimeout function executes asynchronously, allowing the program to continue running without waiting for the timer to finish.

When to Use

Synchronous Functions

Asynchronous Functions

MDN Web Docs: Synchronous vs Asynchronous