0
<html> 

<body>
       Hello World
       <script src="app.js"  charset="utf-8"></script>
</body>
</html>

In my app.js file, I have a lot of variables such as

var choice1_link=[[null,2,null,5,null,5],[null,2,null,5,null,5],[null,2,null,5,null,5]];
var choice2_link=[[null,2,null,4,null,4],[null,2,null,4,null,4],[null,2,null,4,null,4]];
var lastscene=[4,4,4];

I'd like to store these variables in another .js file and import them into my app.js main file. How would I do this? And do I also need to refer the second .js file(where I'm only storing the variables) to the HTML markup?

Puneeth .m
  • 43
  • 5
  • 4
    Does this answer your question? [How do I include a JavaScript file in another JavaScript file?](https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) – Stephen P Aug 05 '21 at 23:16
  • What do you mean by 'store' the variables in another JavaScript file? Why not just manually copy-paste the variables into the file directly if you want them in the file itself? – Obsidian Age Aug 05 '21 at 23:16
  • Because the variables are too many and its decreasing the readability factor by a lot. – Puneeth .m Aug 05 '21 at 23:17

2 Answers2

1

Just put the data in a js file and add the js file to your html before the file you want to use that code in, just like this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <p>Hello world</p>
  <script src="data.js"></script>
  <script src="app.js"></script>
</body>
</html>

Your data you want to use in the app.js file is in the data.js file. Because you embed the data.js file before the app.js file, you can use that code in the app.js file.

fabian
  • 268
  • 3
  • 15
1

Traditionally, all JavaScript files added to a web page share the same global scope. If you declare variables outside of any function, they can be accessed in other files. Of course, files are executed in order, so make sure the file declaring the data is imported before the file using it.

To avoid variable name conflicts, the modern approach is to use JavaScript modules. Instead of having to put many script elements in your HTML file, just put one <script type="module" src="..."></script> and from that main file you can use the import statement to import contents that has been export-ed from other files. Read more about modules here. Note that using modules automatically enables strict mode (which you should be using anyways).

Domino
  • 6,314
  • 1
  • 32
  • 58