JavaScript Tutorial

JavaScript Fetch

fetch(url) loads data. await response.json() parses JSON. Handle errors when the network or the URL fails.

Load data from a URL

fetch(url) asks the network for a resource. It returns a Promise. Withasync / await you write the steps in order: wait for the response, then parse the body.

For a first script, GET is enough — that is the default. You pass a URL and read JSON. You do not need extra options until you send data with POST.

await response.json()

fetch does not give you the object immediately. First you get aResponse. response.json() reads the body and parses it as JSON — the same job as JSON.parse, wired to the network.

Top-level await only works in modules. In a normal page script, put theawait inside an async function and call that function.

Example

<p id="out">Loading…</p>
<script>
  async function loadTodo() {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
    const data = await response.json();
    const out = document.getElementById("out");
    out.textContent = data.title;
    console.log(data);
  }

  loadTodo();
</script>

jsonplaceholder.typicode.com/todos/1is a public sample item. The JSON has userId, id,title, and completed. The page shows the title when the request succeeds.

Click Try it in JavaScript under an example. That opens/javascript/try — a live page and a console. The preview needs a network connection for fetch.

HTTP errors are not throws

fetch rejects (throws, when you await) on a network failure: offline, blocked, a bad host. A 404 or 500 still resolves. The Response arrives with ok set to false. Check response.ok (orresponse.status) before you parse.

Example

<p id="out">Loading…</p>
<script>
  async function loadTodo() {
    const out = document.getElementById("out");
    const url = "https://jsonplaceholder.typicode.com/todos/1";
    const response = await fetch(url);
    if (!response.ok) {
      out.textContent = "Request failed: " + response.status;
      return;
    }
    const data = await response.json();
    out.textContent = data.id + ": " + data.title;
  }

  loadTodo();
</script>

try / catch for the network

Wrap the await calls in try / catch so a downed network does not stop the rest of the page with an uncaught error. Show a short message on the page. Log the error in the console for you.

Example

<p id="out">Loading…</p>
<script>
  async function loadTodo() {
    const out = document.getElementById("out");
    try {
      const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
      if (!response.ok) {
        throw new Error("status " + response.status);
      }
      const data = await response.json();
      out.textContent = data.title;
    } catch (err) {
      out.textContent = "Could not load the todo.";
      console.log(err.message);
    }
  }

  loadTodo();
</script>

What the sample looks like

The sample endpoint returns one object. You read fields with dots, the same as any parsed JSON. There is no special fetch type — after response.json() you have a normal object.

Example

<p id="out"></p>
<script>
  async function loadTodo() {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
    const data = await response.json();
    const out = document.getElementById("out");
    out.textContent =
      "completed: " + data.completed +
      " — user: " + data.userId;
    console.log(JSON.stringify(data, null, 2));
  }

  loadTodo();
</script>

Beginner limits

DoWait on
GET a JSON URLThis chapter
Check response.okThis chapter
try / catch around awaitThis chapter
POST, headers, CORS debuggingLater, when an API requires them

If the console mentions CORS, the server refused this page’s origin. Public demo APIs such as JSONPlaceholder allow browser GET from a tutorial page. Your own server may need extra headers. That is a server setting, not a missing await.

What to remember

  • fetch(url) starts a request. Await the Response.
  • await response.json() parses a JSON body into an object.
  • Check response.ok. A 404 does not throw by itself.
  • Catch network failures and show a message on the page.

You now have the language, the DOM, storage, and fetch. Open the examples shelf next and change a value in /javascript/try.

FAQ: JavaScript Fetch

Common questions about this page.

What is the StudyGrid JavaScript tutorial?

The StudyGrid JavaScript tutorial is a full beginner track: variables, functions, arrays, if/else, the DOM, events, storage, and fetch. Each chapter has copy-and-run examples.

Should I run javascript fetch examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn javascript fetch in this JavaScript JavaScript lesson (JavaScript Fetch).

Is the JavaScript editor the same as Try Python?

No. Try JavaScript is a live page plus a console at /javascript/try. Try Python stays at /try. JavaScript lessons never open the Python editor.

Do I need to install anything to learn JavaScript?

No. Open a chapter, click Try it in JavaScript, and the page and console update in the browser.

Where should I start the JavaScript tutorial?

Start at JavaScript Intro, then Where To, Output, and Syntax. After variables and functions, continue to the DOM and events. Use Next at the bottom of each chapter.

Is the JavaScript tutorial free?

Yes. The JavaScript studio on StudyGrid (studygrid.in) is free: dashboard, chapters, and the live editor.