Fetch vs XMLHttpRequest in JavaScript: Key Differences and Usage
Fetch API is a modern, promise-based way to make web requests in JavaScript, offering simpler syntax and better readability. XMLHttpRequest is the older, callback-based method that is more verbose and less flexible but still supported for legacy code.Quick Comparison
Here is a quick side-by-side comparison of Fetch and XMLHttpRequest based on key factors.
| Factor | Fetch API | XMLHttpRequest |
|---|---|---|
| Syntax | Simple and promise-based | Verbose and callback-based |
| Response Handling | Supports promises and async/await | Uses event listeners and callbacks |
| Browser Support | Modern browsers, IE not supported | All browsers including IE |
| Streaming | Supports streaming responses | No native streaming support |
| Request Cancellation | Supports AbortController | Uses .abort() method |
| Error Handling | Rejects promise on network errors | Requires manual error checks |
Key Differences
The Fetch API uses promises, which makes the code easier to read and write, especially with async/await. It returns a Response object that you can process in various ways, like parsing JSON or text.
In contrast, XMLHttpRequest relies on setting up event handlers like onreadystatechange and checking ready states, which can make the code more complex and harder to follow. It also does not support promises natively.
Another important difference is browser support: Fetch is supported in all modern browsers but not in Internet Explorer, while XMLHttpRequest works everywhere. Fetch also supports features like streaming responses and request cancellation via AbortController, which XMLHttpRequest lacks or handles less cleanly.
Code Comparison
Here is how you make a simple GET request to fetch JSON data using Fetch:
async function fetchData() { try { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); if (!response.ok) { throw new Error('Network response was not ok'); } const data = await response.json(); console.log(data); } catch (error) { console.error('Fetch error:', error); } } fetchData();
XMLHttpRequest Equivalent
This is the equivalent code using XMLHttpRequest to get the same JSON data:
function fetchDataXHR() { const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1'); xhr.responseType = 'json'; xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { console.log(xhr.response); } else { console.error('XHR error: Status', xhr.status); } }; xhr.onerror = function() { console.error('XHR network error'); }; xhr.send(); } fetchDataXHR();
When to Use Which
Choose Fetch when you want cleaner, modern code with promises and async/await support, especially for new projects targeting modern browsers. It is easier to read and supports advanced features like streaming and request cancellation.
Use XMLHttpRequest if you need to support older browsers like Internet Explorer or maintain legacy codebases. It is more verbose but widely supported and reliable for basic requests.