Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Synchronous in JavaScript?
2.1.
Example:
2.2.
JavaScript
2.3.
Output
3.
What is Asynchronous in JavaScript?
3.1.
Example:
3.2.
JavaScript
3.3.
Output:
3.3.1.
Explanation:
4.
Difference Between Synchronous vs Asynchronous JavaScript?
5.
Synchronous examples in JavaScript
5.1.
Reading Files Synchronously
5.1.1.
Explanation
6.
Random Number Generator Without Promise
6.1.
JavaScript
6.1.1.
Explanation
7.
Creating an HTTP Server in Node
7.1.
Explanation
8.
Asynchronous examples in JavaScript
8.1.
Reading files Asynchronously
8.1.1.
Explanation
9.
Using fetch() Function to Request API in Browser
9.1.
Example
9.2.
Explanation
10.
Random Number Generation with Promise Function
10.1.
Example
10.2.
Explanation
11.
How to choose between asynchronous and synchronous programming?
12.
Frequently Asked Questions
12.1.
Q. Are JavaScript promises asynchronous?
12.2.
Q. Why is JavaScript synchronous?
12.3.
Q. Why is callback asynchronous?
13.
Conclusion
Last Updated: Mar 27, 2024
Medium

Synchronous and Asynchronous Javascript

Author Malay Gain
1 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Asynchronous JavaScript is the programming method where operations are run independently allowing the program to continue running while waiting for certain tasks to complete. Synchronous JavaScript is the programming approach where tasks of a program are executed sequentially one at a time.

Synchronous and Asynchronous in Javascript”

What is Synchronous in JavaScript?

Synchronous in Javascript refers to the execution of a program code in a blocking manner. Here tasks are performed sequentially with the help of a call stack. Each individual  task must complete before the next one can begin. This results in delays in execution if any task takes a significant amount of time to execute.

Example:

  • JavaScript

JavaScript

function f1(){
console.log("it is my 1st function");
}

function f2(){
console.log("it is my 2nd function");
f1();
}

f2();

Output

it is my 2nd function
it is my 1st function

 

When the f2() function is called, console.log() is executed first, and then f1(). So, the execution order is sequential here.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is Asynchronous in JavaScript?

Program codes that access or fetch some resource from a server, such as fetching a file from the network, accessing a database and returning data from it, accessing a video stream from a webcam, or executing a function with a delay, the result of such operations may take a longer time to execute. This may result in the javascript engine to halt the execution of the other succeeding code block. Hence for the javascript engine to manage things a bit more efficiently an asynchronous programming method is used.

Asynchronous in JavaScript refers to the execution of code in a non-blocking manner. It allows tasks to be performed independently, enabling the program to continue running while waiting for certain tasks, such as data retrieval or network requests, to complete. Asynchronous code makes use of callbacks, promises, or async/await to handle the results of these tasks once they are finished.

Example:

  • JavaScript

JavaScript

function delay_Greeting() {
setTimeout(function() {
console.log("Hello, Ninja!");
}, 5000); // Wait for 5000 milliseconds (5 seconds)
}

console.log("Start");
delay_Greeting();
console.log("End");

Output:

Start
End
Hello, Ninja!

Explanation:

In this example, the setTimeout function is used to delay the execution of the callback function by 5000 milliseconds (5 seconds).The "Hello, Ninja!" message is displayed after the delay of 5 seconds, showing that the function is executed asynchronously.

Difference Between Synchronous vs Asynchronous JavaScript?

S.No Parameter Synchronous JavaScript Asynchronous JavaScript
1. Execution Order Every statement in a function is executed sequentially.  Every statement in a function is not executed sequentially. It can also execute in parallel.  
2. Dependency on Previous Instructions The execution of the next instruction depends upon the execution of the previous instruction.  The next instruction can execute while the previous one is still executing.
3. Preference Synchronous JavaScript is preferred more.  It is preferred in situations when the execution of some process gets blocked indefinitely.
4. Thread Model Synchronous is a single thread.  Asynchronous is multi-thread in nature. 
5. Speed Synchronous is slower in nature. Asynchronous increases throughout as processes run in parallel.

Synchronous examples in JavaScript

Synchronous JavaScript can be utilized in various scenarios, including the following examples

Reading Files Synchronously

Reading files synchronously is possible with the help of the ‘fs’ module in NodeJs. Synchronous file reading blocks the execution of the program until the file is fully read. This means that the program won't move to the next line of code until the file reading operation is complete. 

Example

const fs = require('fs');

try {
  const data = fs.readFileSync('file1.txt', 'utf8');
  console.log(data);
} catch (error) {
  console.error('Error reading file:', error);
}

 

To run this code, it should be saved in a file (e.g., readfile.js), which is then executed using Node.js

node readfile.js

 

Output

output for reading files synchronously

Explanation

In this example, the readFileSyncron function is used to read the contents of a file named file1.txt synchronously. If the file is successfully read, its contents are stored in the data variable, which can then be further processed or printed. If an error occurs during the file reading process, an error message is displayed.

Random Number Generator Without Promise

It is possible to generate a random number synchronously in JavaScript without using promises, with the help of the Math.random() function.

Example

  • JavaScript

JavaScript

function RandomNumber(a, b) {
 mini = Math.ceil(a);
 maxi = Math.floor(b);
 return Math.floor(Math.random() * (maxi - mini + 1)) + mini;
}
const randomNum = RandomNumber(5, 10);
console.log(randomNum);

 

Output

10

 

Explanation

In the above example, Math.random() generates a random decimal number synchronously between 0 and 1, and then applies mathematical operations to convert it into an integer within the desired range.

Creating an HTTP Server in Node

In synchronous JavaScript, HTTP server in NodeJs involves using the built-in http module. Here the server handles one request at a time and blocks further requests until the current one is completed. 

Example

const http = require('http');

const server1 = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!');
});

server1.listen(3000, 'localhost', () => {
  console.log('Server is up and running on http://localhost:3000');
});

 

To run this code, it should be saved in a file (e.g., server.js), which is then executed using Node.js

node server.js

 

Output

output for creating an HTTP Server in Node synchronously

We can access http://localhost:3000 in a web browser the response "Hello, World!" will be displayed.

output for creating an HTTP Server in Node synchronously

Explanation

After running the code, the server will become active and ready to handle incoming HTTP requests. When accessing http://localhost:3000 in a web browser the response "Hello, World!" will be displayed.

Asynchronous examples in JavaScript

Asynchronous JavaScript can be utilized in various scenarios, including the following examples.

Reading files Asynchronously

To read files asynchronously in JavaScript, we can use the fs module in Node.js. The asynchronous file reading allows the program to continue running while the file is being read, without blocking other tasks.

Example

const fs = require('fs');

fs.readFile('file1.txt', 'utf8', (error, data) => {
  if (error) {
    console.error('Error reading file:', error);
  } else {
    console.log(data);
  }
});

 

To run this code, it should be saved in a file (e.g., readfile.js), which is then executed using Node.js

node readfile.js

Output

output for reading files asynchronously

Explanation

In the above example, the fs.readFile() function is used to read the contents of a file named Doc1.txt asynchronously. The readFile() function accepts a callback function that is executed once the file reading operation is complete. If an error is encountered while reading the file, the error is passed as the first argument to the callback function. If the operation is successful, the data read from the file is passed as the second argument to the callback.

Using fetch() Function to Request API in Browser

The fetch() function is used to make an asynchronous API request in JavaScript. It takes the URL of the API as an argument and returns a Promise that resolves to a Response object. 

Example

async function fetchData() {
  try {
    const response = await fetch('https://apiReq.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log('Error:', error);
  }
}

 

Finally, the fetchData() function is called to initiate the API request.

fetchData();

 

Explanation

In the above example, the fetch() function is used to make an API request. It accepts the URL “https://apiReq.example.com/data” and returns a promise that resolves to a response. 

Random Number Generation with Promise Function

We can generate a random number using a Promise function in asynchronous JavaScript, with the help of the Math.random() function and the Promise constructor. 

Example

function generateRandomNum() {
  return new Promise((resolve, reject) => {
    const randomNum = Math.random();
    if (randomNum <= 0.9) {
      resolve(randomNum);
    } else {
      reject(new Error('Random number is less than 0.9'));
    }
  });
}
generateRandomNum()
  .then((randomNum) => {
    console.log('Random number:', randomNum);
  })
  .catch((error) => {
    console.log('Error:', error);
  });

 

Output

Random number: 0.5991130468508237

 

Explanation

In the above example, the generateRandomNum() function is called. The Promise is then chained with .then() to handle the resolved value (random number) and .catch() to handle any errors. Thus by using Promises, it is possible to generate random numbers asynchronously and handle the results or errors using the .then() and .catch() methods.

How to choose between asynchronous and synchronous programming?

Choosing between asynchronous and synchronous programming in JavaScript depends on the specific requirements and nature of your application:

Synchronous Programming:

  • Use for simpler, linear tasks where one operation depends on the completion of the previous one.
  • Suitable for scenarios where operations need to be executed sequentially, ensuring predictable flow control.
  • May lead to blocking behavior, especially in I/O-bound operations, potentially affecting performance and user experience.

Asynchronous Programming:

  • Ideal for handling non-blocking I/O operations such as network requests, file system operations, or database queries.
  • Enables better utilization of system resources and improves application responsiveness by allowing multiple tasks to execute concurrently.
  • Utilize asynchronous constructs like callbacks, Promises, or async/await to handle asynchronous operations effectively.
  • Essential for modern web applications dealing with real-time updates, interactive interfaces, or heavy server interactions.

Frequently Asked Questions

Q. Are JavaScript promises asynchronous?

Yes, JavaScript promises are asynchronous. Promises are a built-in property in JavaScript that allows programmers to handle asynchronous tasks of a javascript program in a more structured and manageable way. Promises are also used to avoid callback hell.

Q. Why is JavaScript synchronous?

JavaScript is synchronous to maintain simplicity and ensure ease of use, especially in web development. Synchronous execution simplifies handling sequential tasks, but it can lead to blocking behavior in I/O operations, affecting responsiveness.

Q. Why is callback asynchronous?

Callback is asynchronous because it allows the program to continue executing while waiting for the operation to complete. This non-blocking behaviour is important for tasks that may take time to finish. Using callbacks, the program can move to other tasks, improving the efficiency of program.

Conclusion

In this article, we have discussed the Synchronous and Asynchronous Javascript. Understanding the differences between synchronous and asynchronous JavaScript is essential for effective web development. While synchronous execution simplifies sequential tasks, asynchronous programming enables non-blocking I/O operations and improves application responsiveness.

Learn more, Access modifiers in java

To learn more, head over right now to Coding Ninjas to practice important javascript interview problems and crack your interviews like a Ninja!

Happy learning!

Previous article
Callback Hell in Javascript
Next article
Modules in JavaScript
Live masterclass