Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring Empty Variables to make them global

In a JavaScript environment can I declare a variable before a function to make the variable reachable on a global level. For instance:

var a;
function something(){
  a = Math.random()
}

Will this make "a" a global variable?

or is using...

var a = function(){
  var b = Math.random();
  return b;
}
document.write(a())

Really the only way to do it?

Is there a way to make "b" global other than calling the function "a()"?


2 Answers

There are basically 3 ways to declare a global variable:

  1. Declaring it in the global scope, outside of any function scope.
  2. Explicitly assigning it as a property of the window object: window.a = 'foo'.
  3. Not declaring it at all (not recommended). If you omit the var keyword when you first use the variable, it'll be declared globally no matter where in your code that happens.

Note #1: When in strict mode, you'll get an error if you don't declare your variable (as in #3 above).

Note #2: Using the window object to assign a global variable (as in #2 above) works fine in a browser environment, but might not work in other implementations (such as nodejs), since the global scope there is not a window object. If you're using a different environment and want to explicitly assign your global variables, you'll have to be aware of what the global object is called.

like image 151
Joseph Silber Avatar answered Apr 19 '26 20:04

Joseph Silber


Will this make "a" a global variable?

A var declaration makes the variable local to the enclosing scope, which is usually a function one's. If you are executing your code in global scope, then a will be a global variable. You could as well just omit the var, then your variable would be implicitly global (though explicit declaration is better to show your intention).

Is there a way to make "b" global other than calling the function "a()"?

Your b variable is always local to the function a and will never leave it, unless you remove the var.

like image 37
Bergi Avatar answered Apr 19 '26 19:04

Bergi



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!