Closures are functions that refer to variables from their parent environment. To understand them better, let's take a look at the following example:
function parent() { const message = 'Hello World'; function child() { alert (message); } child(); } parent();
In the preceding example, you can see how the child()
function has access to a constant defined in the parent()
function. However, this is a simple example, so let's look at a more interesting one:
function parent() { const message = 'Hello World'; function child() { alert (message); } return child; } const childFN = parent(); childFN();
This time, the parent()
function returned the child()
function, and the child()
function is called after the parent()
function has already been executed. This is counterintuitive to some developers because usually the parent()
function's local members should only exist while the function is being executed. This is what closures are...