CodeZettaInterview Hub

JavaScript · Browser APIs · Fresh / Intern · Comparison

Compare the Fetch API with XMLHttpRequest. When might XHR still appear?

Short Interview Answer

Fetch is promise-based, streaming-friendly, and modern; XHR is older callback/event based. Legacy code and some progress-upload cases still use XHR.

Detailed Explanation

Fetch uses promises, supports `AbortController`, and integrates with streams. It does not reject on HTTP error statuses (only network failures) — you must check `res.ok`. XHR provides upload progress events historically harder with fetch (though modern streams/progress patterns evolve). Cookies/credentials differ by defaults (`credentials` option). Prefer fetch in new code; know XHR for maintenance interviews.

Example

const res = await fetch('/api', { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } });
if (!res.ok) throw new Error('HTTP ' + res.status);

Interview Tip

Call out that fetch doesn't throw on 404 — classic gotcha.

Common Mistake

Assuming `fetch` rejects on 500 responses.

Did you know this answer?