I need a few global variables that I need in all .js
files.
For example, consider the following 4 files:
global.js
js1.js
js2.js
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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With