Scopes
JavaScript variables are only accessible under certain circumstances. While scope is any part of a program where a binding between a variable and value is valid,'lexical scope' refers to the regions in your code where you can refer to a variable directly by its name.
Global Scope
In a simple program without any functions, there is one lexical scope called the global scope.Global scope can be shared across files as a way for different parts of a program to interact.Adding a variable to a program just by itself adds it to the global scope and can be accessed from anywhere else in the program.
Functions
A new lexical scope is created every time you type out a function definition between the two curly braces around the body. While you can still access variables from any broader scopes containing the new one, the variables you create inside the new scope can only be referred to from within that scope.
If you define a function inside another function, you are creating even more 'deeply-nested' lexical scopes where variables will only be available inside that scope:
var car = aCar();
var newJourney = function() {
var map = aMap();
var journey = function() {
var destination = aDestination();
log(car + journey + destination);
};
newJourney();
newJourney()
};
newJourney();
newJourney();