Scope refers to the context of our code. It represents the accessibility of variable or function.
When you declare variable or function that not belongs to any object or function, it's global scope.
Global variable, function can be accessed from everywhere. It's the big advantage of global scope but it's also disadvantage of global scope.
Global variable, function should go into module, object to avoid confusing with local variables, functions.
// global scope
var name = 'Global name';
function global_a () {
}
Variables, functions are not global, it's local scope.
Local variables, functions is declared in function, object, module.
Local variables, functions are not visibale to global scope.
var myFunction = function () {
var name = 'Local Todd';
console.log(name); //Local Todd
};
console.log(name); // Error: name is not defined
Block statement like IF ELSE, FOR, WHILE, SWITCH,.. does not create new scope. Variables defines in block statement will remain it's scope.
if(true) {
var a = 1;
}
console.log(a);// 1
Lexical scope means in nested group funtions, the child one can access to variable and other resources of parent.
But, the parent can not access to local variable, resources in children.
// Scope A
var myFunction = function () {
// Scope Parent
var name = 'i am parent';
// defined in Scope Parent
var myOtherFunction = function () {
// Scope Child: `name` is accessible here!
console.log();
};
};
For each execution context there is a scope chain coupled with it. The scope chain contains the variable object for every execution context in the execution stack.
Exp: function second can use resources defined in first. Function third can use resources defined in second
function first() {
second();
function second() {
third();
function third() {
fourth();
function fourth() {
// do something
}
}
}
}
first();
A closure is created when an inner function want to access to lexical scope resources.
It's likely resources accessor : you have a private variable, and closure function to access to this variable from outside.
function foo() {
var localVar = 'private foo';
return function() {
return localVar;
}
}
var getLocalVariable = foo();
getLocalVariable() // "private foo"