Let say globalX is a global object variable. Lets define a function that takes that variable and inside another function takes same variable and changes the value inside it.
var globalX = [];
function a1(globalX){
a2(globalX);
console.log(globalX);
//it shows "[]" not "[5,10]";
}
function a2(globalX){
globalX = [5,10];
}
a1(globalX);
When I consoled that variable, console shows only parameter value in a1 not changed value in a2 function. How to reference changed value after calling a2?
In browser environments, you can refer to global variables by explicitly referencing the window object:
var reallyGlobalX = window.globalX
In node.js, there is no window object, but global is available:
var reallyGlobalX = global.globalX
Note that the variable must really be global - if it is just another variable from the outer scope, you cannot reach it once the variable has been shadowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With