JavaScript closures works whenever they see the function keyword within another function, the inner function has access to variables in the outer function. Below is an example that shows how closure works in JavaScript.
function foo(x) {
var tmp = 3;
function bar(y) {
console.log(x + y + (++tmp));
}
bar(10);
}
foo(2);
This code will always print 16 because the function bar can access the value x which was defined as an argument to function foo, and from foo, it can also access tmp.
Are you willing to pursue a career in Web Development, here's an opportunity for you Web Developer Certification provided by intellipaat!