3

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. :)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MThead
  • 87
  • 1
  • 2
  • 7

3 Answers3

10

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;
   }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
matcartmill
  • 1,573
  • 2
  • 19
  • 38
6

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.

Fábio Santos
  • 3,899
  • 1
  • 26
  • 31
3

You can assign a key to the 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 the 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 the window scope, otherwise it will just update bar2. If you want to make sure about using the global one, use like window.bar2 = bar1.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mritunjay
  • 25,338
  • 7
  • 55
  • 68