DEV Community

LAKSHMI G
LAKSHMI G

Posted on

Understanding Closure, Fetch, and Axios in JavaScript

What is a Closure:

  • Closure inner function access to outer function’s variables even after the outer function has returned.

  • Inner function remembers variables from where it was created

*example:
*

<script>
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)
 withdraw2(50)
 withdraw2(100)
</script>

Enter fullscreen mode Exit fullscreen mode

Here account creates a private balance
withdraw can access and update that private balance.

What is fetch

  • Fetch is built-in Js function
  • It is return to always Promise(response,reject)
  • promise resolves with a Response object if the request is successful

Response is an object

The Response object has methods to read the data:

.json() → returns a promise that resolves to JSON
.text() → returns plain text
.blob() → returns binary data (images, files)
.status → status code (200 OK status , 404 Not Found status )
.ok → true if status is 200

  • It is used to make the HTTP requests to server
  • Fetch use the Json file formate handling Manualy (.json())

Why we use fetch

  • We want to get data from an API.(Application Programming Interface or file location )

  • We want to send data to a server.

  • You can pass arguments fetch(url is required, options).

  • Here url is require option is optional(method, headers, body)

<script>
fetch("https://fakestoreapi.com/products")
.then((res)=> res.json())
.then(jsonresponse)=>console.log(jsonresponse)
.catch((rej)=>rej.json())
</script>

Enter fullscreen mode Exit fullscreen mode

Axios

  • Axios not a built-in function is a JavaScript library for making HTTP requests.

  • It is automatically converts response to JSON file formate.

  • we can use Axios without installation by adding it CDN script (in your HTML file)in head tag


`  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>`
Enter fullscreen mode Exit fullscreen mode

Example

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

Top comments (0)