A closure in JavaScript is a function that has access to its own lexical scope, even when the function is called outside this scope. Closures are created at the time that the function is instantiated and allow a function to “remember” the environment in which it was created.
In otherwise A closure is a feature in JavaScript where an inner function retains access to the variables of its outer function even after the outer function has returned. This allows for data encapsulation and privacy.
How Does It Works? Let’s Go
const taxCal = (val)=>{ let localTaxRate = 0.05; return function netcal (per){ return (val-(per/100* val)) - (localTaxRate * val); }
}
const finalVal = taxCal(2000);
console.log(finalVal(20));
taxCal
is a higher-order function that takes a single argument, val.It returns a new function, netcal, which takes another argument, per.
The returned function
netcal
calculates the value after applying a percentage reduction. Specifically, it computes:
New Value = (val - (per/100) × val))-(localTaxRate * val)
- Creating a Closure
const finalVal = taxCal(2000);
When
taxCal
is called with the argument 2000, it returns thenetcal
function with val set to 2000.The
netcal
function retains access to the val variable (which is 2000) due to the closure.Using the Returned Function
console.log(finalVal(20));
Here,
finalVal
is thenetcal
function with val already set to 2000.Calling
finalVal(20)
invokes thenetcal
function with per set to 20.The formula used in
netcal
is:
New Value = (2000- (20/100) × 2000))-(0.05 × 2000)
Breaking it down:
20/100 = 0.2; 0.20 × 2000 = 400; 0.05 × 2000 = 100 New Value = (2000−400)-100 = 1500;
`
Break Down the whole process
-
taxCal
defines a local variablelocalTaxRate
and an inner functionnetcal
that accesses this variable. When
taxCal
is called, it returns thenetcal
function.Even after
taxCal
has finished executing,netcal
still has access totaxCal
because of the closure created.
Advantages of Closures
Data Privacy and Encapsulation: Closures help in creating private variables and methods. This means you can hide implementation details and expose only the necessary methods and variables
Maintaining State: Closures allow functions to maintain state across multiple calls without using global variables. This is useful in scenarios where you need to remember previous values or results.
Modular Code: Closures support modularity by allowing you to create functions with encapsulated logic. This makes code easier to maintain and understand.
Asynchronous Code: Closures are frequently used in asynchronous programming (e.g., callbacks, promises) to access variables from the outer function’s scope even after the function has been invoked.
We’ll tackle asynchronous programming later—don’t worry, it’ll be worth the wait!” 👨💻