JavaScript Fetch API Interview Questions and Answers
Review Fetch requests, response handling, HTTP errors, and sending data with the browser Fetch API.
Frequently Asked Questions
Important questions are highlighted in the sections below; select one to jump to its answer.
- What is a Promise and the fetch API in JavaScript?
- Check a response-like object before reading its data.
- What does `fetch()` return?
- Does `fetch()` reject for an HTTP 404 response?
- How do you read JSON from a fetch response?
- How do you set a request method with Fetch?
- What role does CORS play in cross-origin Fetch?
Theoretical JavaScript Interview Questions
A Promise represents the eventual success or failure of an asynchronous operation. The fetch() function makes HTTP requests and returns a Promise that resolves to a Response object. Together, they enable clean asynchronous network requests using .then()/.catch() or async/await.
`fetch()` returns a Promise that fulfills with a `Response` when a response is received. HTTP error statuses such as 404 do not by themselves reject that Promise.
No. A 404 is still an HTTP response, so check `response.ok` or `response.status` and handle it explicitly; the fetch Promise generally rejects for network-level failures or similar request errors.
Call `response.json()`, which returns a Promise for the parsed body. The body is consumed as a stream, so the same response body generally cannot be read again without cloning the response first.
Pass an options object as the second argument, such as `{ method: "POST" }`. The options can also include headers, a body, credentials, and other supported request settings.
For cross-origin requests, the browser applies CORS rules to determine whether JavaScript may access the response. The server must provide appropriate CORS headers; client code cannot bypass that policy.
Serialize the value with `JSON.stringify()` and typically set `Content-Type: application/json`, while specifying a method such as `POST`. The server must accept that content type and body format.
Create an `AbortController`, pass its `signal` in the Fetch options, and call `controller.abort()` when cancellation is needed. The request Promise rejects with an abort-related error, which should be handled separately from other failures.
The response body is a stream, and reading methods consume it. If two consumers need the body, use `response.clone()` before consuming either copy, or parse once and share the resulting data.
A browser may send an `OPTIONS` preflight when a cross-origin request is not CORS-safelisted, for example because of its method or headers. The server's preflight response must authorize the requested origin, method, and headers before the browser sends the actual request.
The client must opt into credentials, and the server must return an explicit allowed origin rather than `*` plus `Access-Control-Allow-Credentials: true`. Cookie policy, including `SameSite`, still applies independently.
Read `response.body` with a stream reader and process each chunk as it arrives, releasing or cancelling the reader when finished early. This avoids buffering the entire body, but the code must handle decoding, backpressure, and stream errors.
In browser contexts, cross-origin redirect handling is constrained by Fetch and CORS; manual mode can expose an opaque-redirect filtered response rather than the redirect details. It should not be treated as a general way to inspect cross-origin `Location` headers.
Retry only failures that are plausibly transient, bound attempts, and use backoff with jitter in production systems. Retrying non-idempotent operations can duplicate effects unless the server supports idempotency keys or equivalent safeguards.
JavaScript Practical and Coding Interview Questions
Problem: Write an async function that rejects a non-OK response and returns JSON for an OK response. Use a local mock response so the example runs without a network.
async function readJson(response) {
if (!response.ok) throw new Error('Request failed: ' + response.status);
return response.json();
}
const response = {
ok: true,
status: 200,
json: async () => ({ items: ['pen', 'book'] }),
};
readJson(response).then((data) => console.log(data));Problem: Use URLSearchParams to read a section and difficulty, and collect every repeated label value into an array.
function readFilters(search) {
const parameters = new URLSearchParams(search);
return {
section: parameters.get('section') ?? '',
difficulty: parameters.get('difficulty') ?? 'any',
labels: parameters.getAll('label'),
};
}
console.log(readFilters('?section=maps&difficulty=medium&label=browser&label=collections'));