Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a global variable referenced already in parameter on a function?

Tags:

javascript

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?

like image 591
Tarık Özgün Güner Avatar asked Feb 23 '26 13:02

Tarık Özgün Güner


1 Answers

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.

like image 111
Robert Rossmann Avatar answered Feb 26 '26 02:02

Robert Rossmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!