DEV Community

SELVAKUMAR R
SELVAKUMAR R

Posted on

Closure, Fetch(), Axios in Java Script

In closure we can access the variable created in outer function and used in the inner function even though outer function return value

We can create the private variable and method in the outer function that can be accessed with in this function only.

Ex:

<script>
function account(amount){
let balance = amount;
function deposite(amt){
balance=balance+amt;
console.log(balance);}

return deposite;
}
const deposit1 = account(1000);
deposit1.deposite(500);
</script>
Enter fullscreen mode Exit fullscreen mode

Output

Fetch():

Fetch () method in Java script is used to get and send the request from the browser

Fetch () method returns the promise as response object once the request is completed

In fetch() we give the url as parameter and we use the .json() method to change the response in json formate to fetch the information

<script>
    // fetch() methon in java script
    fetch("https://fakestoreapi.com/products")
    .then((rep)=>
         rep.json()
    ).then((name)=>console.log(name))
    .catch((rej)=>console.log(rej.json())
    ) 
   </script>
Enter fullscreen mode Exit fullscreen mode

Output:

Axios in Java Script:

It is open source library for making the HTTP request to the server

It Handling the error better than the fetch()

It automatically transforming the request in to json formate.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
     <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

</head>
<body>
    <script>
          axios.get("https://fakestoreapi.com/products")
   .then((name)=>console.log(name))
   .catch((err)=>console.log(err))
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Output:

Top comments (0)