Since you've stated that you're writing JavaScript code to be executed in web browsers, here's what your main.js
file may look like (holding the variable importantVariable):
const importantVariable = 10;
Next, we have another JavaScript file, other.js
(using the variable importantVariable):
console.log(importantVariable);
In the HTML document, where you're willing to use the scripts, include the main.js
BEFORE the other.js
file.
<!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>
<script src="main.js"></script>
<script src="other.js"></script>
</body>
</html>
You should get "10" in the console, which indicates that the variable sharing of one file with other[s] worked successfully.
Explanation: A variable in the global scope should be accessible to all scripts loaded after it is declared.