A Closure is a Javascript feature where a function,enclosed inside another function (outer function), is returned and invoked outside of the outer function.
A closure is formed when the inner function maintains access to variable outside its scope aka lexical scope; access to variables and arguments of the outer function even after the outer has executed.
Let's create a tax calculator closure function to calculate taxes for alcoholic and non-alcoholic drinks based on their tax rates.
const taxCalculator = (vat ) => {
return function taxableAmount (amount) {
const tax = amount * vat / 100;
return tax
}
}
//alcoholic drinks have their on VAT, lets say 16%
const alcoholTax = taxCalculator(16)
const alcoholA = alcoholTax(1200) // an Alcohol that costs 1200
const alcoholB=alcoholTax(800) // an Alcohol that costs 800
//non-alcoholic have their own VAT, let say 12%
const nonAlcoholTax = taxCalculator(12);
const water = nonAlcoholTax(500)
const Juice=nonAlcoholTax(300)
As you can see, each drink will always remember their tax rate based on the whether it is alcoholic drink or non-alcoholic i.e the returned function is invoked outside of taxCalculator
and is able to retrieve the value vat
parameter even though the main function taxCalculator
had been executed.
In react js, JavaScript UI library, event handlers are declared inline on the JSX as such.
<button onClick={handleClick}>Click me</button>
If the event handler has an argument, it will then be invoked inside a function as such.
function ActionButtons(){
const actions = ["Create", "Edit", "Delete"]
const handleAction = (action) => {
switch (action) {
case actions[0]:
//do something
break;
case actions[1]:
//do something
break;
case actions[2]:
//do something
break;
default:
// do nothing
break;
}
}
return (
<div className="flex flex-col md:flex-row w-full p-4 gap-4 ">
{ actions.map(action =>
<button
className="w-full md:w-60"
style={{
backgroundColor: "palevioletred",
color: "white",
outline: "none",
}}
onClick={()=>handleAction(action)}>{action}</button>)}
</div>)
}
Note the handleAction is encapsulated by an arrow function when assigning it to the onclick event handler.
With closure we can simply call handleAction with a action argument then return an inner function that grabs the action argument and performs the rest of the actions like so.
function ActionButtons() {
const actions = ["Create", "Edit", "Delete"];
const handleAction = (action) => {
return function () {
console.log(` ${action} Action button clicked`);
switch (action) {
case actions[0]:
//do something
break;
case actions[1]:
//do something
break;
case actions[2]:
//do something
break;
default:
// do nothing
break;
}
};
};
return (
<div className="flex flex-col md:flex-row w-full p-4 gap-4 justify-between">
{actions.map((action) => (
<button
className="w-full md:w-60"
style={{
backgroundColor: "palevioletred",
color: "white",
outline: "none",
}}
onClick={handleAction(action)}>
{action}
</button>
))}
</div>
);
}
Notice how we invoke the handleAction directly on the OnClick event? also notice we have refactored the handleAction function so that it returns a function performing the necessary actions wity a switch ?
The handleAction is invoked when the component mounts, a closure occurs when the function returned by handleAction grabs and holds onto to the value of the argument on handleAction even though it (handleAction) executed during the first render.
It is a neat way of handling events in Javascript.what do you think?
Top comments (2)
Using JavaScript closures in React allows you to maintain state and encapsulate variables within component functions, enhancing modularity and reusability. For instance, closures can be employed to create private methods or manage component-specific logic without exposing it globally. When integrating functionality like a vat calculator ireland into your React application, closures can help maintain the state of user inputs and calculation results efficiently. By leveraging closures, you can ensure that your VAT calculator remains accurate and responsive, providing users with precise Irish VAT calculations within your React components.
Unfortunately, this is not correct.
Misconceptions About Closures
Jon Randy đī¸ ãģ Sep 27 '23