Closures in JavaScript
Dec 27, 2020
A Closure is a 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.
The closure has three scope chains:
- It has access to its own scope — variables defined between its curly brackets.
- It has access to the outer function’s variables.
- It has access to global variables.
Some Examples Using Closures:
function makeSizer(size) {
return function() {
document.body.style.fontSize = size + 'px';
};
}
var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);
size12
, size14
, and size16
are now functions that resize the body text to 12, 14, and 16 pixels, respectively.