What is the difference between synchronous and asynchronous functions?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Medium
#JavaScript #Functions #Asynchronicity #JS Basics

Brief Answer

Synchronous functions execute immediately and block further code execution until they complete. Asynchronous functions start execution but don’t block the code — they complete later when the result is ready. Promise and async/await are used to work with asynchronous operations.

// Synchronous function
function syncFunc() {
  console.log('Synchronous function');
  return 'done';
}
 
// Asynchronous function with Promise
function asyncFunc() {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('Asynchronous function');
      resolve('done');
    }, 1000);
  });
}
 
// Usage
syncFunc();   // Executes immediately
asyncFunc().then(result => console.log(result));  // Starts execution, but continues code
console.log('Code continues to run'); // Executes immediately
// After 1 second: 'Asynchronous function'
// Then: 'done'

Full Answer

The difference between synchronous and asynchronous functions is like the difference between buying coffee at a café and ordering food for delivery. At a café you wait while they make your drink (synchronously), but at a restaurant you order food and continue doing things while the food is being prepared (asynchronously)! ☕

In modern JavaScript, Promise and async/await are used to work with asynchronous operations, making code more readable and easier to work with.

What are Synchronous Functions

Synchronous functions are regular functions that execute immediately and block further code execution until they complete:

function syncTask() {
  console.log('Start');
  // Executes immediately
  console.log('End');
}
 
syncTask();
console.log('This executes after syncTask');

What are Asynchronous Functions

Asynchronous functions are functions that start execution but don’t block the code. They complete later when the result is ready:

function asyncTask() {
  console.log('Start');
  setTimeout(() => {
    console.log('Completion after 1 second');
  }, 1000);
  console.log('Function completed (but not the task!)');
}
 
asyncTask();
console.log('This executes immediately after asyncTask starts');

Main Differences

Execution Order

// Synchronously
function sync() {
  console.log('1');
  console.log('2');
  console.log('3');
}
 
// Asynchronously
function async() {
  console.log('A');
  setTimeout(() => console.log('C'), 0);
  console.log('B');
}
 
sync(); // Output: 1, 2, 3
async(); // Output: A, B, C

Code Blocking

// Synchronous function blocks everything
function syncDelay() {
  const start = Date.now();
  while (Date.now() - start < 3000) {
    // Useless 3-second delay
  }
  console.log('Synchronous delay completed');
}
 
console.log('Start');
syncDelay(); // Wait 3 seconds
console.log('This appears only after 3 seconds');
 
// Asynchronous function doesn't block
function asyncDelay() {
  setTimeout(() => {
    console.log('Asynchronous delay completed');
  }, 3000);
}
 
console.log('Start');
asyncDelay(); // Don't wait
console.log('This appears immediately');

Simple Examples

Synchronous Functions

// Regular math operations
function add(a, b) {
  return a + b;
}
 
function multiply(a, b) {
  return a * b;
}
 
const sum = add(2, 3);        // 5 (immediately)
const product = multiply(4, 5); // 20 (immediately)

Asynchronous Functions

// Working with network
function fetchData(callback) {
  console.log('Requesting data...');
  setTimeout(() => {
    callback('Data received');
  }, 2000);
}
 
fetchData((data) => {
  console.log(data);
});
console.log('Code continues to run');

When to Use What

Synchronous Functions

// For fast operations
function calculateTax(price) {
  return price * 0.2;
}
 
function formatName(first, last) {
  return first + ' ' + last;
}

Asynchronous Functions

// For long operations
function loadUserData(userId, callback) {
  // Simulating server request
  setTimeout(() => {
    callback({ id: userId, name: 'User ' + userId });
  }, 1000);
}

Promises and async/await

What is a Promise

A Promise is an object representing the result of an asynchronous operation. A Promise has three states:

  • Pending — waiting
  • Fulfilled — successfully completed
  • Rejected — completed with error
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Data received');
  }, 1000);
});
 
// Using Promise
myPromise.then(result => {
  console.log(result); // 'Data received'
});

async/await

async/await is syntactic sugar for working with Promises, making code more readable:

// Function with async returns Promise
async function fetchData() {
  return 'Data';
}
 
// Using await instead of .then()
async function getData() {
  const data = await fetchData(); // Wait for result
  console.log(data); // 'Data'
}
 
getData();

Common Mistakes

Expecting Immediate Result

// ❌ Error — expecting result from asynchronous function
function asyncOperation() {
  let result;
  setTimeout(() => {
    result = 'done';
  }, 1000);
  return result; // undefined!
}
 
const data = asyncOperation();
console.log(data); // undefined
 
// ✅ Correctly — using callback
function asyncOperationCorrect(callback) {
  setTimeout(() => {
    callback('done');
  }, 1000);
}
 
asyncOperationCorrect((data) => {
  console.log(data); // 'done'
});

Confusion with Execution Order

console.log('1');
 
setTimeout(() => {
  console.log('2');
}, 0);
 
console.log('3');
 
// Output: 1, 3, 2 (not 1, 2, 3!)

Simple Rules

  1. Synchronous — execute immediately and block code ⏱️
  2. Asynchronous — don’t block code, complete later ⚡
  3. Order — synchronous code always executes before asynchronous 📋
  4. Result — asynchronous functions return result later 🕐
  5. Usage — synchronous for fast operations, asynchronous for long operations 🎯
  6. Promise — object for working with asynchronous operations 📦
  7. async/await — modern way to work with asynchronous code ✨

Understanding the difference helps write more efficient code and avoid errors with execution order! 💪


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪