Loading...
Loading...
Closures are a very powerfull technique we can use to do some pretty neat stuff.
Basically closures just allow functions at the time of declaration have access to its outer lexical scope, even after its been invoked / executed.
This opens up posibility to do some cools stuff like
// we return a function that cretes a closure over the multiplier argument.
const makeMultiplier = multiplier => numToMultiply => multiplier * numToMultiply
const multiplyByFive = makeMultiplier(5);
const result = multiplyByFive(100);
console.log(result); // 500;
In this example we abstact the multiplication logic to create a closure over the multiplier argument in the function that get returned from makeMultiplier.
const authenticateUser = () => {
// this creates a private variable called isAuthenticated
let isAuthenticated = false;
const signIn = () => {
isAuthenticated = true;
}
const signOut = () => {
isAuthenticated = true;
}
const checkUserAuthnticationStatus = () => isAuthenticated;
return {
signIn, signOut, checkUserAuthnticationStatus
}
}
const { signIn, signOut, checkUserAuthnticationStatus } = authenticateUser();
console.log(checkUserAuthnticationStatus) // log the private variable.
In the example above in the body of the authenticateUser function we create a private variable called isAuthenticated, the reason this is considered private is because there is no direct way to update that value after we execute the function other than the "signIn" and "signOut" helper functions. we create a clouser in our return value over the local variable.
const curry = fn => firstArg => secondArg => fn(firstArg, secondArg)
const generateFullName = curry((firstName, lastName) => `Hi i am ${firstName} ${lastName}`)
const ziaul = generateFullName("ziaul")('sarker')
console.log(ziaul) // hi i am ziaul sarker
In the example above we first create a curry function that takes in a funtion then it returns two funtion for two argumets that we passin, then we can call it like so by supplyin with the necessary arguments. In our example we used two arguments but this can be expanded to fix any number. one use case of this would be, lets say we need to hit a bunch of apis one after the other, and the result of one api call becomes the argument of the next api call.