The Gamer King The Gamer King - 1 year ago 69
Javascript Question

Can a javascript variable be used from a different file

I am making a game and I wanted to know how to use a variable from a different file. Ex:

File 1:

var js = "js";

File 2:


I know it seems kind of weird but I have a reason I am doing it.

Answer Source

Can a javascript variable be used from a different file?

Yes, it can... As long as it's a global variable.

This is because all of the javascript files are loaded into a shared global namespace.

But be warned...

In your HTML, you will need to include the script that declares this variable first. Otherwise it will complain that the variable is undefined.



var globalNumber = 10;


alert(globalNumber); // Will alert "10"


<script src="script1.js"></script>
<script src="script2.js"></script>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download