0
0
JavascriptComparisonBeginner · 4 min read

Fetch vs XMLHttpRequest in JavaScript: Key Differences and Usage

The 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.

FactorFetch APIXMLHttpRequest
SyntaxSimple and promise-basedVerbose and callback-based
Response HandlingSupports promises and async/awaitUses event listeners and callbacks
Browser SupportModern browsers, IE not supportedAll browsers including IE
StreamingSupports streaming responsesNo native streaming support
Request CancellationSupports AbortControllerUses .abort() method
Error HandlingRejects promise on network errorsRequires 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:

javascript
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();
Output
{ userId: 1, id: 1, title: "delectus aut autem", completed: false }
↔️

XMLHttpRequest Equivalent

This is the equivalent code using XMLHttpRequest to get the same JSON data:

javascript
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();
Output
{ userId: 1, id: 1, title: "delectus aut autem", completed: false }
🎯

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.

Key Takeaways

Fetch API offers simpler, promise-based syntax and better modern features.
XMLHttpRequest is callback-based and supports all browsers including IE.
Use Fetch for new projects targeting modern browsers for cleaner code.
Use XMLHttpRequest for legacy support or older browser compatibility.
Fetch supports streaming and request cancellation; XMLHttpRequest does not.