Using variables across scripts

I have a public JavaScript file and a private JavaScript file. I want a variable from the public file to be used in the private one without the use of HTML. Is there a way to do that?

I’ve tried using import and export but I can’t get it to work

Theoretically this should work with localstorage but I couldn’t get that to work right (I’ve tried this before). The little bit of help that I can offer is this: you can run functions from one JS file in another really easily (and this might solve the problem depending on what you’re doing). However, it does require the use of HTML.

<!-- In your HTML file add this: -->
<script src="script1.js">
<script src="script2.js">

Any functions in script1.js can now be executed by script2.js. It’s not exactly what you’re asking but it’s all I could do when I tried to do this. Sorry I couldn’t be of more help.

If you don’t want to use another script tag, then you can do this:


<script src="main.js" type="module"></script>

The important part there is type="module", which allows you to import other files.


import { myFunction } from "./otherFile.js";


And then finally inside of otherFile.js


function myFunction() {
    # do stuff

export { myFunction };

So now by making main.js a module, you can import things from other files by using the import and export keywords. And here is a nice explanation of js modules and importing and exporting.