Synchronous vs Asynchronous Code in JavaScript

Day 19/50 – JavaScript Interview Question? Question: What is the difference between synchronous and asynchronous code? Simple Answer: Synchronous code executes line by line, blocking subsequent code until the current operation completes. Asynchronous code allows other operations to run while waiting for long-running tasks (like API calls) to complete. 🧠 Why it matters in real projects: Asynchronous code prevents UI freezing during network requests, file operations, or heavy computations. Modern web apps rely heavily on async patterns (Promises, async/await) to maintain responsive user interfaces while handling background tasks. 💡 One common mistake: Forgetting to use await with async functions, causing code to continue executing before the promise resolves, leading to undefined values or race conditions. 📌 Bonus: // Synchronous - blocks execution console.log('1'); const result = expensiveOperation(); // Everything waits console.log('2'); console.log(result); // Asynchronous - non-blocking console.log('1'); fetch('/api/data').then(result => { console.log(result); // Executes later }); console.log('2'); // Doesn't wait for fetch // async/await - cleaner async code async function getData() { console.log('1'); const result = await fetch('/api/data'); // Waits here console.log(result); console.log('2'); } // Common mistake async function wrong() { const data = fetch('/api/data'); // Missing await! console.log(data); // Promise object, not the data } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews

To view or add a comment, sign in

Explore content categories