I want to understand, when I send an globalArray as a parameter to a recursive function, and assign the same array (localArray) to the globalArray, how is the memory allocation happening in javascript. I know that each recursion will have it's own callstack, and it will have it's own copy of variables, but since I am passing a globalArray into the function, will a copy of the localArray be always stored as a new array in each callstack?
If I were to achieve the localArray as an incremental copy of the same localArray variable for each execution context, how would I be achieving that?
Please view the image and code snippet
function testFunction(localArray){
globalArray = localArray;
if(itr < 5) {
globalArray.push(1);
itr++;
testFunction(localArray);
}
}
var globalArray = [1,2,3];
var itr = 0;
testFunction(globalArray);
[added later to this question]
But if I were to modify the code a bit where I were to make the localArray as null, the globalArray would still be holding data, if it was a value which was referred.
function testFunction(localArray){
globalArray = localArray;
localArray = null;
if(itr < 5) {
globalArray.push(1);
itr++;
testFunction(globalArray);
}
}
var globalArray = [1,2,3];
var itr = 0;
testFunction(globalArray);