0

If I defined a function that depends on (uses) a global variable in its module, what would happen if I exported it and tried to call it outside that module?

I have tried it and found that it just works normally, although I don't have access to that variable (it's not defined in my scope). So I want to make sure whether I understand this or not, is this just like the closure functions and the function gets its variables from the lexical scope?

PS: My question is related to the ES6 modules feature.

#Adding real simple Example

This is my html: simply nothing but a script

<!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 type="module" src="app.js"></script>
  </body>
</html>

This is my module file:

let globalVariable = "I cannot be accessed outised this module";
export function testFunction() {
  console.log(globalVariable);
}

This my app.js file:

import { testFunction } from "./module.js";

testFunction();

Although globalVariable is not accessible in app.js the message has been printed in the console.

Jimmy
  • 27
  • 6
  • 2
    Which variables a function has access to only depends on where and how it is defined. It doesn't matter where it is called. That's basically lexical vs dynamic scope. – Felix Kling May 13 '21 at 08:07
  • 1
    It really isn’t clear what you are asking. Try providing a [mcve] – Quentin May 13 '21 at 08:08
  • 1
    "*is this just like the closure functions and the function gets its variables from the lexical scope?*" no, it's not "just like" a closure. It literally ***is*** exactly a closure. All functions are closures in JavaScript. – VLAZ May 13 '21 at 08:27
  • 1
    "*My question is related to the ES6 modules feature.*" hardly. It's just a base JS concept. The fact that there are modules is irrelevant. Sure, I suppose it *could* have been the case that functions defined in modules weren't closures but 1. that would be a great change in how all of the language works so far. 2. it would defeat the purpose of having modules. – VLAZ May 13 '21 at 08:30
  • @VLAZ Thank you so much for you clarification, Can you add it as an answer so that I can accept it? – Jimmy May 13 '21 at 08:41

1 Answers1

2
let globalVariable = "I cannot be accessed outised this module";

That is not a global. It is just a variable in the scope of the module.

export function testFunction() {
  console.log(globalVariable);
}

This function accesses the variable named globalVariable no matter where it (the function) is passed to, just like any other closure.

Further reading: How do JavaScript closures work?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335