Javascript is lexically scoped
What does that mean?
It means the scope is determined where the variable is physically located in your file. Not where the code is executed from.
Example:
function exampleB() {
console.log(a); //'a' is defined at compiled time, it does not know who is going to invoke exampleB();
}
function exampleA() {
var a = 20;
exampleB()
}
var a = 30;
exampleA();
exampleB();
Output:
"30"
"30"
function exampleA() {
var a = 20;
console.log("Example A: " + a);
function exampleB() {
console.log("Example B: "+ a); -> Results in 20, because the 'a' is physically located in exampleA().
}
exampleB();
}
exampleA();
Output:
"Example A: 20"
"Example B: 20"
If Javascript was Dynamically scoped, then:
function exampleB() {
console.log(a); -> 'a' would be 20 due to exampleB variable 'a' would override the global variable 'a'
}
function exampleA() {
var a = 20;
exampleB()
}
var a = 30;
exampleA(); -> Results in 20
exampleB(); -> Results in 20