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.
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.
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.
In your HTML, you will need to include the script that declares this variable first. Otherwise it will complain that the variable is undefined.
script1.js
var globalNumber = 10;
script2.js
alert(globalNumber); // Will alert "10"
index.html
<script src="script1.js"></script>
<script src="script2.js"></script>