Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 39 ยท Practice and Review

AJAX, JSON and Fetch Interview Questions

26 AJAX, JSON and fetch interview questions with concise answers and code: fetch vs XHR, CORS, error handling, race conditions, security, plus live puzzles.

Almost every front-end or full-stack interview includes questions about talking to servers from the browser. Some check vocabulary ("what is CORS?"), some check whether you know the traps ("does fetch throw on a 404?"), and some ask how you would design something safely ("how do you store a login token?"). This page collects 26 of the most common ones, grouped by level: Junior, Mid and Senior.

Each answer is hidden. Read the question, answer it out loud as if the interviewer were sitting across from you, and only then open the answer to compare. After the lists you will find three code-reading puzzles you can run: predict the output first, then press Run.

A strong answer has three parts: a one-sentence definition, a tiny example or consequence, and a trade-off ("...but it costs X, so I would use it when Y"). Interviewers remember candidates who mention trade-offs.

Junior level

1. What is AJAX?

AJAX means making HTTP requests from JavaScript in the background and updating part of the page with the answer, without a full page reload. The name stands for "Asynchronous JavaScript and XML", but today the data is almost always JSON and the tool is fetch(). The page stays interactive while the request is in flight, which is why you must handle loading and error states yourself. See What Is AJAX?.

2. What is JSON, and how is it different from a JavaScript object literal?

JSON is a text format for data, based on JavaScript syntax but stricter: keys must be double-quoted strings, strings must use double quotes, and there are no comments, trailing commas, undefined, functions or NaN. An object literal is code that creates a live object; JSON is only text until you call JSON.parse. See JSON Syntax and Data Types.

3. What do JSON.parse and JSON.stringify do, and which values cannot survive a round trip?

JSON.stringify turns a value into JSON text; JSON.parse turns text back into a value. Functions and undefined are dropped from objects (or become null in arrays), NaN and Infinity become null, a Date becomes an ISO string and comes back as a plain string, Map and Set become {}, and a BigInt throws. JSON.parse throws a SyntaxError on bad input, so wrap it in try/catch when the text comes from outside. See parse and stringify.

4. What does fetch() return?

A promise that resolves to a Response object as soon as the response headers arrive. The body has not necessarily been downloaded yet; you read it with a second promise-returning call such as response.json() or response.text(). So a typical call needs two awaits. See Your First fetch() Request.

5. Does fetch reject its promise on a 404 or 500?

No. The promise rejects only when the request could not complete at all (network down, DNS failure, blocked by CORS, aborted). A 404 or 500 is a successful exchange, so the promise resolves and you must check response.ok (true for statuses 200 to 299) or response.status yourself and throw if needed. This is the most common fetch bug. See Handling Errors in fetch.

6. How do you send JSON with a POST request?

Set the method, tell the server the format, and serialize the body yourself:

JavaScript
const response = await fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Mia' }),
});

fetch will not stringify objects for you, and without the Content-Type header many servers will refuse to parse the body (often with a 415 or an empty result). See Sending Data.

7. What is the difference between GET, POST, PUT, PATCH and DELETE?

GET reads (safe, cacheable, no body). POST creates or triggers an action. PUT replaces a resource entirely, PATCH changes part of it, and DELETE removes it. GET, PUT and DELETE are idempotent: repeating them leaves the same final state. POST is not, which matters for retries. See HTTP for AJAX Developers.

8. Which HTTP status codes should every developer know?

200 OK, 201 Created, 204 No Content (success, empty body), 301/302 redirects, 304 Not Modified (cache is still valid), 400 bad request, 401 not authenticated, 403 not allowed, 404 not found, 409 conflict, 422 validation failed, 429 too many requests, 500 server error, 502/503/504 gateway or availability problems. The first digit is the class: 2 success, 3 redirect, 4 client's fault, 5 server's fault.

Mid level

9. fetch vs XMLHttpRequest vs axios: how do they differ?

XMLHttpRequest is the old, event-based API (onreadystatechange, onload); it still offers upload progress events. fetch is promise-based, integrates with streams and AbortController, and is the modern standard. Libraries like axios add conveniences on top: automatic JSON handling, interceptors, rejecting on non-2xx statuses. You can get most of that by writing a small wrapper yourself (Project: A Reusable API Client). See XMLHttpRequest and Legacy AJAX.

10. Why can a Response body only be read once, and what does clone() do?

The body is a stream: reading consumes it, so a second response.json() fails because the body is already used (response.bodyUsed is true). If two places need the body, call response.clone() before reading, and read each copy. See The Response Object.

11. What is CORS, and does it protect my server?

CORS (cross-origin resource sharing) is a browser rule: a page may only read responses from another origin (scheme, host and port) if that server opts in with headers such as Access-Control-Allow-Origin. For requests that could have side effects (custom headers, JSON Content-Type, methods other than GET/HEAD/POST) the browser first sends an OPTIONS preflight to ask permission. CORS does not protect the server: tools like curl ignore it, and the request still reaches the server. It protects the user's browser from other sites reading data with the user's credentials. See Headers, Auth and CORS Basics.

12. How do cookies work with fetch across origins?

By default fetch sends cookies only to the same origin (credentials: 'same-origin'). For cross-origin calls you need credentials: 'include' and a server that answers with Access-Control-Allow-Credentials: true and a specific Access-Control-Allow-Origin (a wildcard * is rejected for credentialed requests). Cookies are also subject to their SameSite attribute, which can stop them being sent on cross-site requests at all.

13. How do you design error handling for fetch?

Separate the failure kinds: network failure (the promise rejects), HTTP error (check response.ok, read the error body), invalid body (json() throws), timeout and cancellation. Wrap all of it in one helper that throws typed errors, then map each type to a user-friendly message in one place, with a retry option where it makes sense. Never show raw text such as "Failed to fetch" to users. See Handling Errors in fetch.

14. When would you use Promise.all, allSettled, race and any with requests?

Promise.all: you need every result and one failure should fail the whole thing. Promise.allSettled: you want every outcome, including failures (partial dashboards). Promise.race: the first to settle wins (often a request against a timeout). Promise.any: the first to succeed wins (the same data from several mirrors). See Async/Await for Requests.

15. What is wrong with awaiting inside a loop, or with forEach(async ...)?

for (const id of ids) { await fetch(...) } runs requests one after another: total time is the sum. If the requests are independent, start them together with Promise.all(ids.map(...)). forEach ignores the promises its async callback returns, so code after it runs before the work finishes and errors escape unnoticed. Use for...of for sequential work and map plus Promise.all for parallel work (see puzzle 2 below).

16. How do you cancel a request or add a timeout?

Create an AbortController, pass controller.signal to fetch, and call controller.abort(); the promise rejects with an AbortError. For a timeout use AbortSignal.timeout(ms) (rejects with a TimeoutError), and combine it with a user's signal using AbortSignal.any([...]). Aborting stops waiting for the response; the server may still have processed the request. See Cancelling Requests and Timeouts.

17. What is a race condition in a live search, and how do you fix it?

Responses can arrive in a different order than the requests were sent, so a slow answer for "ca" can overwrite the fresh answer for "cat". Fixes: abort the previous request when a new one starts (and ignore the AbortError), or tag each request with a counter and ignore responses that are not the latest. Debouncing the input also reduces the number of requests. See Live Search, Pagination and Infinite Scroll.

18. Debounce vs throttle: what is the difference?

Debounce waits until the user has stopped for N ms and then runs once (search-as-you-type). Throttle runs at most once every N ms while events keep coming (scroll or resize handlers). Debounce needs a quiet period; throttle guarantees a steady rate.

19. How do you avoid fetching the same data again and again?

At several levels: an in-memory Map with a time-to-live; HTTP caching headers (Cache-Control, ETag with If-None-Match, which lets the server answer 304 Not Modified with no body); and the stale-while-revalidate pattern (show cached data immediately, refresh it in the background). Choose the TTL by how bad stale data would be. See Caching and Polling.

20. Polling, Server-Sent Events or WebSockets: how do you choose?

Polling (repeated requests) is simplest and works everywhere, but wastes requests and adds latency. Server-Sent Events give a one-way server-to-client stream over plain HTTP with automatic reconnection; ideal for notifications and live feeds. WebSockets are two-way and low-latency (chat, games, collaboration) but need more infrastructure. Pick the simplest one that meets the latency and direction you need. See Streaming and Real-Time APIs.

sequenceDiagram
  participant P as Page (shop.example)
  participant B as Browser
  participant A as API (api.example)
  P->>B: fetch(api.example, JSON POST)
  B->>A: OPTIONS (preflight): may I send this?
  A-->>B: Access-Control-Allow-Origin, -Methods, -Headers
  B->>A: the real POST
  A-->>B: response with Access-Control-Allow-Origin
  B-->>P: response is readable

A preflighted CORS request: the browser asks first, and only then sends the real request. If the answer lacks the right headers, JavaScript gets a generic network error.

Senior level

21. How can data from an API lead to XSS, and how do you prevent it?

If you build HTML from API data (innerHTML, template strings inserted as markup), a value like <img src=x onerror=...> becomes executable code. Prevent it by creating elements and setting textContent, using frameworks' automatic escaping, never passing untrusted data to innerHTML, eval or javascript: URLs, sanitizing with a well-reviewed library when you truly need rich HTML, and adding a Content Security Policy as a second layer. The rule: treat server data as untrusted, even from your own backend. See AJAX Security.

22. What is CSRF, and how is it prevented?

Cross-site request forgery tricks a logged-in user's browser into sending a request to your site from another site; the browser attaches the user's cookies automatically. Defenses: SameSite=Lax or Strict cookies, anti-CSRF tokens sent in a header or hidden field, checking the Origin or Sec-Fetch-Site header on the server, and requiring non-simple requests (such as JSON with a custom header) that trigger a CORS preflight. Credentials sent manually in an Authorization header are not attached automatically, so they are not CSRF-prone.

23. Where should you store an authentication token in a web app?

There is no free lunch. localStorage is readable by any script on the page, so one XSS bug leaks the token. An HttpOnly, Secure, SameSite cookie cannot be read by JavaScript (good against token theft) but is sent automatically, so you need CSRF protection. Keeping a short-lived access token only in memory and refreshing it with an HttpOnly cookie is a common compromise. Whatever you choose, never ship secrets such as API keys in front-end code.

24. How do you retry requests safely?

Retry only idempotent requests, or make writes idempotent with an idempotency key header the server uses to ignore duplicates. Retry only errors that can pass (network failures, timeouts, 429, 502/503/504), wait with exponential backoff plus jitter, respect Retry-After, and cap both attempts and delay. See Retries, Backoff and Resilience.

25. Offset vs cursor pagination: what are the trade-offs?

Offset (?page=3 or ?offset=40) is simple and allows jumping to any page, but when rows are inserted or deleted between requests items can be skipped or repeated, and large offsets get slow. Cursor pagination (?after=abc123) resumes from a stable position, stays fast and consistent for feeds, but cannot jump to page 50 directly. For very large payloads consider streaming or NDJSON (one JSON object per line) so the client can process data as it arrives.

26. Why should you validate API responses, and what are the options?

TypeScript types and your expectations do not exist at runtime: a server bug, version change or attacker can send any shape. Validate at the boundary, before the data reaches the rest of the code: hand-written type guards for small cases, or a schema validator (JSON Schema, or a validation library) for larger ones. Fail with a clear error and show a safe fallback. See Validating JSON Data.

Code-reading puzzles

Puzzle 1. Predict the output, in order. Then answer: why does then run for a 404?

JS Puzzle 1: a 404 and a used body

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The catch never runs: a 404 is a normal resolved response, so then runs with ok equal to false. Second reads fail with a TypeError (the exact message differs between browsers), and clone() before reading gives each reader its own copy.

Puzzle 2. What is logged first, and why is forEach the wrong tool here?

JS Puzzle 2: forEach with async callbacks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

forEach calls each async callback and moves on, ignoring the returned promises, so "after forEach" prints before any "finished" line. for...of waits for each step. map with Promise.all starts all three and waits for the slowest.

Puzzle 3. Which keys survive a JSON round trip, and what do they look like afterwards?

JS Puzzle 3: what JSON keeps

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Undefined and function values vanish from objects but become null inside arrays, NaN and Infinity become null, the Date returns as a string, the Map is an empty object, the last duplicate key wins, and single quotes and BigInt are errors. A reviver and replacer can fix most of these.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A fetch call receives a 500 response. What happens to the promise?

    fetch rejects only when the request cannot complete (network failure, CORS block, abort). Any HTTP status, including 500, resolves normally.
  2. 2. Which statement about CORS is true?

    CORS is a browser-side rule driven by response headers. The server can still receive the request, and non-browser clients ignore the rules.
  3. 3. Why is forEach(async ...) a poor way to run asynchronous work and wait for it?

    forEach discards return values. Use for...of for sequential work, or map plus Promise.all for parallel work you can await.
  4. 4. Which pair is a sensible retry policy for a failed request?

    Retrying only safe, repeatable requests after errors that may disappear, with growing and randomized waits and a hard limit, protects both user data and a struggling server.
  5. 5. Which is the safest way to show a username received from an API in the page?

    textContent treats the value as plain text and never as markup, which prevents script injection through data.

Summary

  • Know the vocabulary: AJAX, JSON, Response, idempotent, preflight, CORS, CSRF, XSS, backoff.
  • The classic traps: fetch does not reject on HTTP errors, a body can be read once, JSON drops undefined, functions and the Date type, and forEach does not await.
  • Cancel with AbortController and AbortSignal.timeout(), and ignore stale responses in live search.
  • Retry only idempotent requests and only errors that can pass, with backoff and jitter.
  • Treat all data as untrusted: render with textContent, validate shapes, and keep secrets out of front-end code.
  • Practice answering out loud in three parts: definition, example, trade-off.

Next: AJAX, JSON and Fetch Cheat Sheet