Ask coding questions

← Back to all posts
How to import variables in js
LukeWright (287)

is there a way for you to say import variables from on js document to another? Thanks for the help.

Comments
hotnewtop
SameeraMurthy (110)

@LukeWright, it depends on if you are on NodeJS or in the browser.

If you are in the browser:

<script src="script.js"></script>

If you do this, the JavaScript variables are automatically shared between the files you link in your HTML (it exists in the globally shared window variable).

If you are in NodeJS:

const script = require("./script.js");

When you do this, the variables are shared, but you also can specify what the JavaScript file (module) returns, with module.exports.
For example, in script.js:

module.exports = "Hello World";

And then, you can get the value in your main js file.

const script = require("./script.js");
console.log(script);

And it will return:

Hello World

I hope this helps!

RYANTADIPARTHI (6018)

Solution

here's how. In the first file, put a var.

var variable = "something"

now in the main file, import it.

import { variable } from './path/to/FILENAME.js';

like that. Put the file name in that filename.js
It should work

Rak2006 (14)

You don't need to import variables, if you have the script tags in order I think variables should work in every js file.

19wintersp (1142)

Is this frontend JS or NodeJS? In frontend, the code has to be run in the browser. If you link both files in the document, any variables declaredat the top-level with var will be in the shared global scope (window). For NodeJS, export the variable.