Even if the code you have posted is not JavaScript, you are essentially right. A function () { … }
creates a scope and »inner a inner scope« can access the variables from the »outer«
var a = 10, b = 20;
(function () {
var b = 100;
console.log(a); //10
console.log(b); //100
(function() {
var c = 333;
})();
console.log(c) //undefined
})();
It is notable to say that the scope, a function is defined within, is saved with the function. This means:
function A (a) {
var b = 100;
return function (c) {
console.log(a, b, c);
}
}
var afx = A(10);
afx(666); //10, 100, 666;
However, Javascript does not provide blockscope. So:
for (var i = 0; i < 10; i++) { … }
console.log(i) //9
the variable is not »scoped« to the block.
BUT ES6 and the new keyword let
, to define variables, change this. So:
for (let i = 0; i < 10; i++) { … }
console.log(i); // ReferenceError: i is not defined (using babel to transpile)
So in future versions of JS, also Blockscoping is possible like this:
{
let i = '#';
console.log(i); //#
}
console.log(i); // ReferenceError: i is not defined