Puneeth .m
Puneeth .m

Reputation: 43

How to store variables of javascript in another .js file?

<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?

Upvotes: 0

Views: 1215

Answers (2)

Domino
Domino

Reputation: 6768

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).

Upvotes: 1

fabian
fabian

Reputation: 158

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.

Upvotes: 1

Related Questions