Advertisement
Advanced JavaScript, Networking: Fetch, XHR, WebSockets & CORS

How does a WebSocket connection differ fundamentally from repeated fetch() requests?

Short answer

A WebSocket establishes a single persistent, full-duplex connection after an initial HTTP handshake, allowing both client and server to send messages to each other at any time with minimal overhead — unlike fetch(), which requires a brand-new HTTP request/response cycle (with…

Save JavaScript mock interview
Advertisement
AModel answer
A WebSocket establishes a single persistent, full-duplex connection after an initial HTTP handshake, allowing both client and server to send messages to each other at any time with minimal overhead — unlike fetch(), which requires a brand-new HTTP request/response cycle (with its own headers and TCP overhead) for every single exchange.
const socket = new WebSocket('wss://example.com/chat');
socket.onmessage = (event) => console.log('Received:', event.data);
socket.onopen = () => socket.send('Hello server!');
Real-world example
Building a live chat application or real-time collaborative editor where the server needs to push updates instantly.
Likely follow-ups
  • How does a WebSocket's initial handshake relate to the standard HTTP protocol?
Related topics