30. Event Loops, Memory, Web APIs, Testing, and Build Tools
Why Understanding Event Loops and Memory Matters
JavaScript is single-threaded but handles asynchronous tasks efficiently thanks to the event loop. Understanding how the event loop works, how memory is allocated, and how to use Web APIs and testing tools is essential for writing performant, reliable apps.
The Event Loop Explained
The event loop manages execution of code, handling events and async operations without blocking the main thread. Tasks are queued in the macrotask and microtask queues.
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
Promise.resolve().then(() => console.log('Promise'));
console.log('End');
// Output order: Start, End, Promise, TimeoutExplanation: synchronous code runs first, microtasks (Promises) run next, and macrotasks (setTimeout) run after.
Memory Management
JavaScript uses automatic garbage collection, freeing memory from objects that are no longer reachable. Proper memory handling is crucial to prevent leaks, especially in long-running apps.
// Avoiding memory leaks
function createElement() {
const element = document.createElement('div');
document.body.appendChild(element);
return () => document.body.removeChild(element);
}
const cleanup = createElement();
cleanup(); // Remove element to free memoryWeb APIs
JavaScript can access browser-provided APIs like DOM manipulation, Fetch, Web Storage, and Canvas. These APIs run outside the main thread and interact with the event loop.
// Example: Fetch API
async function getTodos() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
console.log(data);
} catch (err) {
console.error(err);
}
}
getTodos();Testing JavaScript Code
Testing ensures your code behaves as expected and reduces bugs. Popular tools include Jest, Mocha, and Cypress for unit, integration, and end-to-end testing.
// Jest example
test('adds two numbers', () => {
function add(a, b) { return a + b; }
expect(add(2,3)).toBe(5);
});Build Tools & Bundlers
Modern JS apps use build tools like Webpack, Vite, and Rollup to bundle, minify, and optimize code. These tools handle module resolution, transpilation, and hot reloading.
// Example: npm scripts
"scripts": {
"dev": "vite",
"build": "vite build",
"test": "jest"
}Mini Challenge
1. Create a script that fetches 5 posts asynchronously and logs them in order using Promises. 2. Demonstrate memory cleanup by creating and removing DOM elements dynamically. 3. Write a simple unit test using Jest for a function that calculates factorial. 4. Set up a Vite project, create two JS modules, and import them correctly in your main file.