Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a global variable in a .js file

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?

like image 835
kp11 Avatar asked Jun 03 '09 11:06

kp11


People also ask

Are there global variables in JS?

Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.

How do you declare a global variable?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.


1 Answers

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.

like image 73
PatrikAkerstrand Avatar answered Sep 24 '22 06:09

PatrikAkerstrand