JavaScript fetch basics

Beginner
6 min read
Updated: Nov 2026

Definition and Usage

The common pattern is const res = await fetch(url), verify res.ok, then await res.json(). This page uses a mock Response so the example runs offline.

JavaScript Syntax

JavaScript
async function getUser() {
  const res = {
    ok: true,
    status: 200,
    async json() { return { id: 7, name: "Ada" }; }
  };
  if (!res.ok) throw new Error("HTTP " + res.status);
  return res.json();
}
getUser().then((u) => console.log(u.name));
Try it Editor

How It Works

  1. Mock res. Stands in for await fetch(url).
  2. Guard. Throw when not ok.
  3. Parse. json() returns data.

Examples

Example 1 — Reading text

Use text() for plain bodies.

JavaScript
async function run() {
  const res = { async text() { return "hello"; } };
  console.log(await res.text());
}
run();
Try it Editor

How It Works

  1. text() returns a string promise.

Example 2 — Pass headers

Second argument options.

JavaScript
const init = { headers: { Accept: "application/json" } };
console.log(init.headers.Accept);
Try it Editor

How It Works

  1. Real fetch(url, init) uses this shape.

Frequently Asked Questions

Any HTTP(S) endpoint your page is allowed to call (CORS permitting).
Modern Node has global fetch. Older Node needs a polyfill or node-fetch.

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