Synchronous and Asynchronous Code

Introduction

In this lesson, we’ll explore the concepts of synchronous and asynchronous code in JavaScript. They directly impact how your code executes, especially when dealing with tasks like fetching data or handling user interactions.

Synchronous Code

Definition and Characteristics:

  • Synchronous code in JavaScript is executed in sequence, meaning each statement waits for the previous one to finish before executing.
  • It’s straightforward and easy to follow but can lead to performance issues if a line of code takes time to complete (e.g., a complex calculation).

Example:

javascript
	function calculateSum(a, b) {
	    return a + b;
	}
	
	console.log('Start');
	console.log(calculateSum(2, 3));  // Synchronously calculates sum
	console.log('End');

Output:

txt
	Start
	5
	End

Asynchronous Code

Definition and Characteristics:

  • Asynchronous code allows JavaScript to perform other tasks while waiting for an operation to complete.
  • It’s essential for operations that take an indeterminate amount of time, like API requests or reading files.

Example:

javascript
	console.log('Start');
	
	setTimeout(() => {
	    console.log('Inside timeout');
	}, 2000);
	
	console.log('End');

Output:

txt
	Start
	End
	Inside timeout

Conclusion

In this lesson, we’ve seen how synchronous code executes in a straightforward, line-by-line manner, while asynchronous code allows JavaScript to handle tasks that take an unknown amount of time without blocking the main thread. As a web developer, balancing these two approaches is key to creating responsive and efficient applications.