Closures are great and unique in JavaScript because they make variables or arguments available to inner functions and keep them alive even after the outer function has returned. Closures are utilized in the majority of JS design patterns.
function getFullName(a, b) {
return a + b;
}
function makeFullName(fn) {
return function(firstName) {
return function(secondName) {
return fn(firstName, secondName);
}
}
}
makeFullName(getFullName)("Stack")("overflow"); // Stackoverflow
A closure is an inner function that has access to the variables of the outer (enclosing) function—the scope chain. The closure has three scope chains: it may access its own scope (variables declared between its curly brackets), the outer function's variables, and global variables.
The inner function has access not just to the variables of the outer function, but also to its parameters. However, even though the inner function may call the outer function's parameters directly, it cannot call the outer function's arguments object.
A closure is created by nesting one function within another.