How to declare a global variable in a .js file

kp11 picture kp11 · Jun 3, 2009 · Viewed 207.3k times · Source

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?

Answer

PatrikAkerstrand picture PatrikAkerstrand · Jun 3, 2009

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.