Variable scoping continues to confound me (see my sample code below). I have three questions for my understanding, however, the bottom line is that I need metricsArray available in Position4 for further processing.
Q1: I have initialized the " metricsArray " array variable at the top of my function which I thought meant it had global scope in the entire function… is this correct? I have tried both let and var statements and neither change the results below.
Q2: If I try setting the return variables from myFunction ( metricsArray_A and/or metricsArray_B ) below to metricsArray , then I get a warning that the variable is already declared in the upper scope indicating that I am doing something incorrect. Regardless of the warning, Position1 is the only situation where the metricsArray contains data. Also, if I comment out the initialization line of code at the top of the function, then Position2, Position3 and Position4 all complain that metricsArray is not defined. Where should metricsArray be declared?
Q3: From the console.log, the only Position that contains data in the metricsArray variable is Position1. In other words, it appears to me that the global scope is not being held. What am I doing wrong?
Any advice would be most appreciated. I will buy a virtual doughnut and a cup of coffee for anyone that can help me out here!
Thanks,
Jay
async function initalizeMetrics(secArr) {
let metricsArray = [];
//Main Loop
secArr.forEach(async function (sec) {
await getSection(sec).then((text) => {
let newSection = sec.replace(/Upd/, “Orig”)
//////// Call myFunction and return metricsArray_A
myFunction(sec, text).then(( **metricsArray_A** ) => {
console.log("metricsArray_A = " + metricsArray_A)
})
//////// Call myFunction and return metricsArray_B
myFunction(newSection, text).then(( **metricsArray_B** ) => {
console.log("metricsArray_B = " + metricsArray_B)
[u]**metricsArray**[/u] = metricsArray_B;
console.log("Position1 - metricsArray = " + [u]**metricsArray**[/u] ) // <-Has data
})
console.log("Position2 - metricsArray = " + [u]**metricsArray**[/u] ) // <-Empty
})
console.log("Position3 - metricsArray = " + [u]**metricsArray**[/u] ) // <-Empty
});
console.log("Position4 - metricsArray = " + [u]**metricsArray**[/u] ) // <-Empty
}