Brain Busters
QuizzesMock TestsGamesLibrary
UpdatesCommunityAboutContactPremium
Brain BustersLearning and Exam Intelligence

A student learning app built for practice discipline, exam simulation, and visible improvement.

Move from reading to execution with guided quizzes, mock tests, performance signals, and current exam updates in one system.

Student-first
Built for focused learners
More than content
Practice, revise, and measure
Progress system
Study with exam-ready feedback

Platform

  • Practice Quizzes
  • Mock Tests
  • Brain Games
  • Learning Library
  • Premium Plans

Resources

  • About Us
  • Exam Updates
  • Community
  • Contact
Weekly Signals

Join the intelligence loop

Receive product updates, study prompts, and exam alerts without the noise.

Location
Azamgarh, Uttar Pradesh, India
Support Line
+91 9161060447
Direct Email
support@brainbusters.in

© 2026 Brain Busters. Practice with intent.

PrivacyTermsSitemap
    Back to library
    Learning article
    Web Development
    JavaScript

    What is Fetch?

    fetch is a JavaScript function used to make HTTP requests (like getting or sending data) to servers from a website or application. It is part of the modern web API, built into browsers, so you dont need to import any libraries to use it.

    RC

    R.S. Chauhan

    Brain Busters editorial

    January 23, 2025
    4 min read
    0 likes

    Article snapshot

    Read with revision in mind.

    Use the article to understand the topic, identify weak areas, and move back into quizzes with more context.

    Best for concept review
    Start here before timed practice if the topic feels rusty.
    Revision friendly
    Use the tags and related posts to build a tighter study path around the same theme.
    Discuss and clarify
    Add a comment if you want examples, clarifications, or a follow-up explanation.

    fetch is a JavaScript function used to make HTTP requests (like getting or sending data) to servers from a website or application. It is part of the modern web API, built into browsers, so you don’t need to import any libraries to use it.

    Think of fetch as a way for your app to "talk" to another computer (usually a server) over the internet.

    For example:

    • When you load a webpage, it might fetch data from a database to display.
    • A weather app might fetch the current weather data from an API.
    • When you submit a form, it might fetch or send that information to a server.

    Why Use fetch?

    1. To Communicate With APIs: Websites or apps often use APIs to get data (like weather data, user profiles, or news articles).
    2. Efficient & Modern: fetch is simpler and more powerful than older ways like XMLHttpRequest (XHR).
    3. Promises-Based: It uses promises, which makes handling asynchronous code easier and cleaner.

    How to Use fetch?

    Here’s the syntax:

     

    fetch(url, options)
      .then((response) => {
        // handle the response here
      })
      .catch((error) => {
        // handle errors here
      });
    

     

    Basic Terms:

    1. url: The endpoint where you’re making the request.
    2. options (optional): An object to specify the request type (GET, POST, etc.), headers, body data, etc.

    Using fetch with Different HTTP Methods

    1. GET Request (Fetching Data):

    This is used to retrieve data from a server.

    Example:

    fetch("https://api.example.com/data")
      .then((response) => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json(); // Parse the JSON response
      })
      .then((data) => {
        console.log(data); // Use the data
      })
      .catch((error) => {
        console.error("There was a problem with the fetch:", error);
      });
    

    2. POST Request (Sending Data):

    This is used to send data to a server (e.g., submitting a form).

    Example:

    fetch("https://api.example.com/data", {
      method: "POST", // Specify the HTTP method
      headers: {
        "Content-Type": "application/json", // Tell the server you're sending JSON
      },
      body: JSON.stringify({ name: "John", age: 30 }), // The data to send
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json(); // Parse the response
      })
      .then((data) => {
        console.log("Data saved:", data);
      })
      .catch((error) => {
        console.error("Error:", error);
      });
    

    3. PUT Request (Updating Data):

    This is used to update existing data on a server.

    Example:

    fetch("https://api.example.com/data/1", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: "Updated Name", age: 35 }),
    })
      .then((response) => response.json())
      .then((data) => console.log("Data updated:", data))
      .catch((error) => console.error("Error:", error));
    

    4. DELETE Request (Deleting Data):

    This is used to delete data from a server.

    Example:

     
    fetch("https://api.example.com/data/1", {
      method: "DELETE",
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error("Failed to delete");
        }
        console.log("Data deleted successfully");
      })
      .catch((error) => console.error("Error:", error));
    

    Important Features of fetch:

    1. Promise-Based:

      • fetch returns a promise.
      • If the request succeeds, the promise is resolved.
      • If it fails, the promise is rejected.
    2. Response Object:

      • The response object contains information like status codes (200, 404, etc.) and methods to read the data (json(), text(), etc.).
    3. Error Handling:

      • If the request fails (e.g., no internet), you can catch errors using .catch.

    Why Is fetch Better?

    1. Modern and Flexible:

      • It’s simpler and more powerful than older methods like XMLHttpRequest.
    2. Supports JSON Easily:

      • Since most APIs use JSON, you can parse it easily with response.json().
    3. Handles Cross-Origin Requests:

      • It works with APIs that require CORS (Cross-Origin Resource Sharing).

    Example: Complete Flow

    Let’s assume you have an API for a task manager. Here's how you could use fetch to:

    1. Get tasks
    2. Add a new task
    3. Delete a task
    // 1. Get tasks
    fetch("https://api.example.com/tasks")
      .then((response) => response.json())
      .then((tasks) => console.log("Tasks:", tasks))
      .catch((error) => console.error("Error fetching tasks:", error));
    // 2. Add a new task
    
    fetch("https://api.example.com/tasks", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ title: "New Task", completed: false }),
    })
      .then((response) => response.json())
      .then((task) => console.log("Task added:", task))
      .catch((error) => console.error("Error adding task:", error));
    
    // 3. Delete a task
    fetch("https://api.example.com/tasks/1", {
      method: "DELETE",
    })
      .then((response) => {
        if (response.ok) {
          console.log("Task deleted successfully");
        } else {
          console.error("Error deleting task");
        }
      })
      .catch((error) => console.error("Error:", error));
    

    Topics and tags

    Continue from this topic

    Practice next

    Related quizzes

    JavaScript Variable

    In JavaScript, a variable is a container that stores data values. Think of it like a box that you can put different things in. These "things" could be numbers, text, or even more complex information.

    Discussion

    Comments (0)

    Keep comments specific so learners can benefit from the discussion.

    No comments yet.

    Start the discussion with a question or a study insight.

    Quick facts

    Use this article as

    Primary topicWeb Development
    Read time4 minutes
    Comments0
    UpdatedJanuary 26, 2025

    Author

    RC
    R.S. Chauhan
    Published January 23, 2025

    Tagged with

    programming
    javascript
    web development
    Browse library