In JavaScript, scope is the set of variables, objects, and functions that you have access. In the other hand current context of your code.
Lexical scope - A function within another function, the inner function has access to the scope in the outer function, this is called Lexical Scope or Closure - also referred to as Static Scope.
// Scope A
var myFunction = function () {
// Scope B
var name = 'Todd'; // defined in Scope B
var myOtherFunction = function () {
// Scope C: `name` is accessible here!
};
};
var name = 'Todd';
var scope1 = function () {
// name is available here
var scope2 = function () {
// name is available here too
var scope3 = function () {
// name is also available here!
};
};
};
When resolving a variable, JavaScript starts at the innermost scope and searches outwards until it finds the variable/object/function it was looking for.
(function () {
var x = "Hello!!"; // I will invoke myself
})();
A closure is the combination of a function bundled together with references to its surrounding lexical environment. As like lexical scope a closure gives access to an outer function’s scope from an inner function.
Simple way A closure is an inner function that has access to the outer function’s variables—scope chain.
reference: https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36#.uy94feq01 https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/#closures http://javascriptissexy.com/understand-javascript-closures-with-ease/
simply define a function inside another function and expose it. To expose a function, return it or pass it to another function.
The inner function will have access to the variables in the outer function scope, even after the outer function has returned.
var sayHello = function (name) {
var text = 'Hello, ' + name;
return function () {
console.log(text);
};
};
var helloTodd = sayHello('Todd');
helloTodd(); // will call the closure and log 'Hello, Todd'