Closure, Fetch and Axios in Javascript



This content originally appeared on DEV Community and was authored by VIDHYA VARSHINI

Closure:
A closure is a strong capability in JavaScript that enables an inner function to reach variables from its outer function, even when the outer function has completed execution.

This behavior allows for the creation of private variables and methods that cannot be accessed directly from outside the function.
Closures are commonly used for data privacy, state management, and callbacks.

<script>
function account(initialAmount) {
    let balance = initialAmount;  

    function deposit(amount) {
        balance = balance + amount;
        console.log(balance);
    }

    return deposit;
}

const deposit1 = account(1000);
deposit1(500); 
</script>

Output: 1500

Fetch: This is used to get data from a server and send data to a server. It returns promise as a return statement. This works asynchronously and does not block the code. This gets ‘url’, ‘options’ as arguments.

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

Axios: This is a open source library for making HTTP request. It automatically converts response to JSON file format.

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


This content originally appeared on DEV Community and was authored by VIDHYA VARSHINI