The Gamer King The Gamer King - 3 months ago 8
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:

alert(js);


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

Answer

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.

Example

script1.js

var globalNumber = 10;

script2.js

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

index.html

<script src="script1.js"></script>
<script src="script2.js"></script>