Declare a global variable between two scripts

Let's assume that you have the following index.html:

html
<!DOCTYPE html>
<html>
<head>
    <meta charset = "utf-8">
    <title>Hello, world</title>
</head>
<body>
    <p>Hello, world</p>
    <script src = "./one.js" type = "module"></script>
    <script src = "./two.js" type = "module"></script>
</body>
</html>

As scripts have type = "module", if you declare a variable on one.js:

javascript
var x = 20;

And you try to access it on two.js:

javascript
console.log(x);
// undefined

You can solve it by declaring the variable as a window variable on one.js:

javascript
window.x = 20;

Then, on two.js:

javascript
console.log(x);
// 20

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.