JavaScript Fetch

Beginner
6 min read
Updated: Nov 2026

Definition and Usage

fetch(url) starts a network request and returns a Promise of a Response. Check response.ok, then read the body with json(), text(), or other methods.

TopicSummary
basicscall fetch and read JSON.
POST JSONsend a JSON body with headers.
HeadersHTTP header map.
Requestbuild a request object.
Responsestatus, ok, and body helpers.

JavaScript Syntax

JavaScript
// Demo shape (offline-friendly mock)
const response = { ok: true, status: 200, async json() { return { id: 1 }; } };
if (!response.ok) throw new Error("HTTP " + response.status);
response.json().then((data) => console.log(data.id));
Try it Editor

How It Works

  1. Response. Represents the result.
  2. ok. True for 2xx statuses.
  3. json(). Parses the body.

Examples

Example 1 — Mock response flow

Same control flow as real fetch.

JavaScript
async function load() {
  const res = { ok: true, async json() { return { name: "Ada" }; } };
  const data = await res.json();
  console.log(data.name);
}
load();
Try it Editor

How It Works

  1. Pretend fetch returned res.
  2. Await json().
  3. Use the data.

Example 2 — HTTP error check

Treat non-OK as failure.

JavaScript
async function load() {
  const res = { ok: false, status: 404 };
  if (!res.ok) {
    console.log("HTTP " + res.status);
    return;
  }
}
load();
Try it Editor

How It Works

  1. fetch does not throw on 404.
  2. You check ok/status.

Frequently Asked Questions

The modern browser API for HTTP requests. It returns promises instead of using callbacks like XMLHttpRequest.
No. Only network failures reject. Check response.ok or status yourself.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful