Ask coding questions

← Back to all posts
Importing variables in Javascript
Aidan72

ok so say I have two files, "main1.js" and "main2.js", I have a variable in main1.js that I want to be in sync with main2.js, (let's say the variable is "num") would I do:

in main2.js or is this wrong?

Voters
veryHappyCoder
muhammadsidik
Aidan72
Comments
hotnewtop
eankeen

From the repl you linked, it won't work because you did not designate your scripts to use ES Modules :).

Like this:

When you're importing using ES Modules, you don't add scripts tags for them in your HTML because your're asking the server for the file with this line (in your main2.js)

It's worth noting that when you write the filename, you have to prefix the file the name with some absolute or relative path "/main.js", "./main.js", or to some url: "https://example.com/main.js"

I actually created a repl that shows a working example. :)

If you want more info, I would recommend reading this article. MDN has some wonderful docs for imports and exports.

I read your post again, and if you want a much simpler solution, you can just designate num as a global variable and use that, like in this repl.

Vandesm14

Remove the "var" from the statement and it should work.

Aidan72

@Vandesm14

didnt work :/

Vandesm14

@Aidan72 can you send a link to your repl?

Aidan72