Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a local variable into a global in JavaScript [duplicate]

Tags:

javascript

How can I make a local variable inside a function into a global in JavaScript?

P.S: Just pure JavaScript, no jQuery.

P.P.S.: Nothing toooo complicated, thanks. :)

like image 479
MThead Avatar asked Jun 13 '26 13:06

MThead


2 Answers

You can do the following to access a global inside of a function.

Any variable created outside the scope of a function can be referenced inside of a function.

Var myGlobalVar;

Function myFunction(){
   if(....) {
        myGlobalVar = 1;
   }
}
like image 174
matcartmill Avatar answered Jun 16 '26 02:06

matcartmill


You don't.

You can copy a local variable to the global scope by doing window.myVar = myVar (replacing window by whatever is your global object), but if you reassign the local one, the global copy won't follow.

like image 20
Fábio Santos Avatar answered Jun 16 '26 02:06

Fábio Santos



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!