How to make a local variable into Global? JavaScript
This question already has an answer here:
You can do the following to access a global inside of a function.
Any variable created outside the scope of a function can be reference inside of a function.
Var myGlobalVar;
Function myFunction(){
if(....) {
myGlobalVar = 1;
}
}
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.
You can assign a key to window
object. It'll be a global variable.
function foo(){
var bar1; //local variable
bar1 = 11;
window.bar2 = bar1; //bar2 will be global with same value.
}
OR
In pure javascript if you will declare a variable without var
anywhere, it will be in global scope.
function foo(){
var bar1; //local variable
bar1 = 11;
bar2 = bar1; //bar2 will be global with same value.
}
Note:- In the above text if bar2
won't be declared yet, it will go to window
scope, otherwise it will just update the bar2
. If you want to make sure about a global one say like window.bar2=bar1
.