DEV Community

Dev Ananth Arul
Dev Ananth Arul

Posted on

Closure, Fetch() and Axios in JavaScript

Closure
The closure occurs when an inner function has access to variables in its outer function (outer scope), even when the outer function has finished executing.

function account (amount){
        let balance= amount;
        function withdraw(amt){
            balance= balance-amt;
            console.log(balance);

        }
           return withdraw;
       }
       const withdraw1=account(1000);
             withdraw1(100);
        const withdraw2=account(500);
            withdraw1(50);
Enter fullscreen mode Exit fullscreen mode

Output
900
450

Fetch()
Fetch() returns a promise that resolves to a response object.
Url: The API endpoint from which data is fetched.
.response.json(): Parases the response as JSON.
.catch(error): Handles any errors that occur during the request.

 fetch("https://fakestoreapi.com/products")
      .then((res)=>{
       return res.json();
      })
      .then((json)=>{
        console.log(json);
      })
      .catch((err)=>{
        console.log(err);
      })
Enter fullscreen mode Exit fullscreen mode

Axios
Axios is a open source javascript library use to make an HTTP request from web browsers. Automatically parses JSON(no need for response.json()).

 axios.get("https://fakestoreapi.com/products")
      .then((json)=>{
        console.log(json);
      })
      .catch((err)=>{
        console.log(err);
      })
Enter fullscreen mode Exit fullscreen mode

Top comments (0)