DEV Community

Cover image for Asynchronous and synchronous JavaScript Basics!
Avinash Kumar
Avinash Kumar

Posted on

Asynchronous and synchronous JavaScript Basics!

Asynchronous and synchronous are two ways in which a program can execute:

Synchronous execution means that the program will execute each line of code one at a time, in the order that they appear. If a line of code takes a long time to execute (for example, making a network request), the program will stop and wait for it to finish before moving on to the next line.

Asynchronous execution means that the program can execute multiple lines of code at the same time. This is useful when you have long-running tasks, such as making network requests, because it allows the program to do other work while waiting for the task to complete.

JavaScript is an asynchronous language, which means that it can execute multiple lines of code at the same time. This is made possible through the use of events and callbacks.

An event is an action that occurs in the program, such as a user clicking a button or a network request completing. A callback is a function that is called when an event occurs.

For example, consider the following code:

function makeNetworkRequest() {
  // make a network request and log the response
}

makeNetworkRequest();
console.log('This line of code will run before the network request completes');
Enter fullscreen mode Exit fullscreen mode

In this case, the makeNetworkRequest function makes a network request and logs the response. The console.log statement will run before the network request completes, because the program is executing synchronously.

To make this code execute asynchronously, we can use a callback:

function makeNetworkRequest(callback) {
  // make a network request and log the response
  callback();
}

makeNetworkRequest(function() {
  console.log('This line of code will run after the network request completes');
});
console.log('This line of code will run before the network request completes');
Enter fullscreen mode Exit fullscreen mode

In this case, the makeNetworkRequest function makes a network request and logs the response. When the network request completes, the callback function is called. This allows the program to continue executing while the network request is in progress.

Asynchronous execution is an important concept in JavaScript, and it is used extensively in modern web development. It allows programs to be more efficient and responsive by allowing them to do multiple tasks at the same time.

Top comments (0)