A Closure Case
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment) In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
Closures can be used in the scenario of a try-catch
block where you want a method to be called inside both of the scopes, depending on the return value of an execution.
In the following snippet, we need to invoke publish()
but with a set of common values except for status
, which would be the result of the method invoked within the try-catch block.
We can totally go ahead with invoking publish with the values repeated in both the try-catch
scopes like below
This results in repeated code - which is fine but we can go one step and refactor this with closures.
The publishMetric function will be like below
Closures are quite useful like this and can help us in many scenarios when dealing with asynchronous situations.
Reference
Updated on