0

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.

  • As long as you define your variable globally (`window.js = 'js';`) and it is defined before your (File 2) is referenced, you should have no problem using it. – George Sep 07 '16 at 12:10
  • 1
    no need to do `window.js`, `var js` is enough – pwolaq Sep 07 '16 at 12:11
  • @pwolaq In a global scope, yes. If defined in a function, then no. – George Sep 07 '16 at 12:11
  • Maybe. Maybe not. It depends how you are running the JS. "Embedded in a webpage" and "In Node.JS" will give very different answers. – Quentin Sep 07 '16 at 12:13
  • also be advised that polluting global scope is not a good practice, perhaps `AMD` is solution to your problem - check out `RequireJS` or some other related framework – pwolaq Sep 07 '16 at 12:13
  • Alright, thanks, I'll try it out =D – The Gamer King Sep 07 '16 at 12:14
  • Javascript files are like any other file, as long as you invoke them, they will execute, therefore, if you import your file 1 BEFORE using the contents of file 1 it should be fine. e.g in your html file: `` ` ` Should work as long as your browser has access to file1.js (if yopu are working on the nodejs server side, use require("moduleName") to import, but the way variables work is the same. – E.Serra Sep 07 '16 at 12:15
  • What if it's an array though? – The Gamer King Sep 07 '16 at 12:15
  • Any var. `var foo=[1,2,3,4,5]; var bar = { "x":"1", "y":function() { alert(bar.x) }}` – mplungjan Sep 07 '16 at 12:27
  • what about functions? – The Gamer King Sep 07 '16 at 16:52

1 Answers1

1

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>
byxor
  • 5,930
  • 4
  • 27
  • 44