Monday, 20 January 2025

JavaScript Closures, Callbacks and Callback Hell, Currying.



JavaScript Closures, Callbacks and Callback Hell, Currying Function.

1. JavaScript Closures.

   Closures is the combination of a bundled function.

   Closures gives you access to an outer function's scope from an inner function.

function init() {
    var name = 'Mozilla';
    function displayName() {
        console.log('name --->', name);
        // output : name ---> Mozilla
    }
    displayName();
}
init();

2. JavaScript Callbacks.

   Function passed as an argument.

   
function test1(name, callback) {
    console.log('name---->', name);    
    callback();    
}

function test2() {
    console.log('test2---->');    
}

test1("Ankit", test2);
//output :
// name----> Ankit
// test2---->

3. JavaScript Callback Hell.

   Every callback depends / waits for the previous callback.

setTimeout(() => {
    console.log('test 1--->');
    setTimeout(() => {
        console.log('test 2--->');
    }, 2000);    
}, 5000);
// output :
// test 1--->
// test 2--->

4. JavaScript Currying Function.

function sendEmail(to) {
    return function (from) {
        return function (body) {            
            return to + ' - ' + from + ' - ' + body;
        }
    }
}

let to = sendEmail('to@gmail.com');
let from = to('from@gmail.com');
console.log(from('Body data'));
// output : to@gmail.com - from@gmail.com - Body data.

function sendEmail(to) {
    return function (from) {
        return function (body) {            
            return to + ' - ' + from + ' - ' + body;
        }
    }
}

console.log(sendEmail('to@gmail.com')('from@gmail.com')('Body data.'));
// output : to@gmail.com - from@gmail.com - Body data.

//using arrow function
const sendemail = (to) => (from) => (body) => { return to + ' - ' + from + ' - ' + body};
console.log('sendemail--->', sendemail('to@gmail.com')('from@gmail.com')('Body data.'));
// output : sendemail---> to@gmail.com - from@gmail.com - Body data.


No comments:

Post a Comment