What is Web Workers in JavaScript?
Answer
Web Workers allow running JavaScript code in a background thread, separate from the main UI thread, preventing heavy computations from blocking the UI. Main thread creates a worker: const worker = new Worker("worker.js"). Communicate via postMessage() and message events — data is copied (not shared) via structured cloning. Main: worker.postMessage(data); worker.onmessage = e => console.log(e.data). Worker file: self.onmessage = e => { const result = heavyComputation(e.data); self.postMessage(result); }. Workers do NOT have access to DOM, window, or document. Workers can use: fetch(), IndexedDB, WebSockets, importScripts(), and other Web APIs. Shared Workers: multiple tabs/windows can access the same worker. Service Workers: act as a proxy between the web app and network — enable offline functionality, push notifications, and background sync (Progressive Web Apps). Terminate: worker.terminate().