Closures are nothing but a statefull functions.
A closure is an inner function that has access to outer function’s variables in addition to it’s own variable and global variables.In simple term a closure is a function inside a function.Closures using Lexical scoping in which function have access to global and outer variables.Below is a sample example of Javascript closure.
function employee() {
var employee_dept = 'IT';
return {
getDept: function () {
return employee_dept;
},
setDept: function (new_dept) {
employee_dept = new_name;
}
}
}
var emp1 = employee (); // In this juncture, the employee_dept outer function has returned.
mjID.getDept(); // IT
mjID.setDept('Account'); // Changes the outer function's variable
mjID.getDept(); //outputs Account
Closures prevents your important variable to be modified accidently.It can be only modified by itself.