This seems to be a topic that has been asked several times before but i'm really struggling to find a succinct explanation. Closest I could find was this (What is the scope of variables in JavaScript?) but there are several aspects I still don't quite understand. As you have probably guessed I'm fairly new to javascript but this aspect seems crucial to understand fully if I am ever going to get anywhere with it.
So consider a program comprised of several nested functions:
function functionA() {
var functionAVariable = "A";
}
function functionB() {
var functionBVariable = "B";
}
function functionC() {
var functionCVariable = "C";
function functionD() {
var functionDVariable = "D";
}
}
var globalVariable = "G";
var mainFunction = function () {
var mainFunctionVariable = "M";
functionA();
functionB();
functionC();
};
From my understanding all functions will have access to globalVariable
and functionA
, functionB
and functionC
will have access to mainFunctionVariable
.
Where I start to get a bit confused is when we add deeper nests to the overall program as with functionD
. Will functionD
have access to all higher level function variable that currently wrap it or will it only have access to the immediate parent, functionC
?