Closures are used to create private variables and functions in JavaScript. A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables—a scope chain. 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, and it has access to the global variables.
Example:
function outerFunction(x) {
let innerVariable = 3;
function innerFunction(y) {
return x + y + innerVariable;
}
return innerFunction;
}
let innerFunc = outerFunction(5);
console.log(innerFunc(2)); // 10