91

I need a few global variables that I need in all .js files.

For example, consider the following 4 files:

  1. global.js
  2. js1.js
  3. js2.js
  4. js3.js

Is there a way that I can declare 3 global variables in global.js and access them in any of the other 3 .js files considering I load all the above 4 files into a HTML document?

Can someone please tell me if this is possible or is there a work around to achieve this?

Matt
  • 74,352
  • 26
  • 153
  • 180
kp11
  • 2,055
  • 6
  • 22
  • 25

5 Answers5

98

Just define your variables in global.js outside a function scope:

// global.js
var global1 = "I'm a global!";
var global2 = "So am I!";

// other js-file
function testGlobal () {
    alert(global1);
}

To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file:

<html>
    <head>
        <!-- Include global.js first -->
        <script src="/YOUR_PATH/global.js" type="text/javascript"></script>
        <!-- Now we can reference variables, objects, functions etc. 
             defined in global.js -->
        <script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>
    </head>
    [...]
</html>

You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.

PatrikAkerstrand
  • 45,315
  • 11
  • 79
  • 94
  • 4
    While this answer is correct I would recommend that you Google Javascript variable scoping to get a better understanding and possibly avoid doing things this exact way. – aleemb Jun 03 '09 at 12:16
  • 1
    Agreed. I always try to scope all functions and variables in a common "namespace" to avoid cluttering and conflicts. Usually I name it as an abbrevation of the project or company. – PatrikAkerstrand Jun 03 '09 at 12:40
  • Downvoting this answer and the others like it because it assumes that the global variable is going to be created in a global scope, and it also requires that the first mention of the variable be in the global scope before all other mentions. – Andrew May 03 '17 at 19:51
  • 2
    @Andrew This answer was written eight years ago. For all intents and purposes, it was correct back then. If you want to actually make a contribution, you might want to suggest an edit instead? – PatrikAkerstrand May 07 '17 at 06:30
  • @PatrikAkerstrand The dating actually makes no difference. The other answers that use a global object are sufficient; I explained why this is not. – Andrew May 08 '17 at 14:03
  • How is this global if you are using `var`? You have to ommit `var` to make it global. – Black Jun 13 '19 at 06:53
92

The recommended approach is:

window.greeting = "Hello World!"

You can then access it within any function:

function foo() {

   alert(greeting); // Hello World!
   alert(window["greeting"]); // Hello World!
   alert(window.greeting); // Hello World! (recommended)

}

This approach is preferred for two reasons.

  1. The intent is explicit. The use of the var keyword can easily lead to declaring global vars that were intended to be local or vice versa. This sort of variable scoping is a point of confusion for a lot of Javascript developers. So as a general rule, I make sure all variable declarations are preceded with the keyword var or the prefix window.

  2. You standardize this syntax for reading the variables this way as well which means that a locally scoped var doesn't clobber the global var or vice versa. For example what happens here is ambiguous:

 

 greeting = "Aloha";

 function foo() {
     greeting = "Hello"; // overrides global!
 }

 function bar(greeting) {
   alert(greeting);
 }

 foo();
 bar("Howdy"); // does it alert "Hello" or "Howdy" ?

However, this is much cleaner and less error prone (you don't really need to remember all the variable scoping rules):

 function foo() {
     window.greeting = "Hello";
 }

 function bar(greeting) {
   alert(greeting);
 }

 foo();
 bar("Howdy"); // alerts "Howdy"
aleemb
  • 31,265
  • 19
  • 98
  • 114
  • Attaching variables to the window should work across all browsers (and is also the approach I take, +1!). – Dandy Dec 02 '13 at 21:01
  • 1
    @Dan, if you declare "var testvar='hello';" outside a function, it is automatically added to the window object and you can access it with "window.testvar". – zkent Dec 23 '13 at 18:30
  • 1
    @zkent, that's right, but using Window object is still better cuz u may want to turn your code into sth like coffee later. – NamiW Feb 08 '14 at 11:36
  • Is it better to use Window rather than Document prefix? – Andrew Jun 05 '14 at 09:07
7

As mentioned above, there are issues with using the top-most scope in your script file. Here is another issue: The script file might be run from a context that is not the global context in some run-time environment.

It has been proposed to assign the global to window directly. But that is also run-time dependent and does not work in Node etc. It goes to show that portable global variable management needs some careful consideration and extra effort. Maybe they will fix it in future ECMS versions!

For now, I would recommend something like this to support proper global management for all run-time environments:

/**
 * Exports the given object into the global context.
 */
var exportGlobal = function(name, object) {
    if (typeof(global) !== "undefined")  {
        // Node.js
        global[name] = object;
    }
    else if (typeof(window) !== "undefined") {
        // JS with GUI (usually browser)
        window[name] = object;
    }
    else {
        throw new Error("Unkown run-time environment. Currently only browsers and Node.js are supported.");
    }
};


// export exportGlobal itself
exportGlobal("exportGlobal", exportGlobal);

// create a new global namespace
exportGlobal("someothernamespace", {});

It's a bit more typing, but it makes your global variable management future-proof.

Disclaimer: Part of this idea came to me when looking at previous versions of stacktrace.js.

I reckon, one can also use Webpack or other tools to get more reliable and less hackish detection of the run-time environment.

Domi
  • 22,151
  • 15
  • 92
  • 122
7

Have you tried it?

If you do:

var HI = 'Hello World';

In global.js. And then do:

alert(HI);

In js1.js it will alert it fine. You just have to include global.js prior to the rest in the HTML document.

The only catch is that you have to declare it in the window's scope (not inside any functions).

You could just nix the var part and create them that way, but it's not good practice.

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
2

Yes you can access them. You should declare them in 'public space' (outside any functions) as:

var globalvar1 = 'value';

You can access them later on, also in other files.

Ropstah
  • 17,538
  • 24
  • 120
  • 194