I have the code:
// lib.js var a = "a"; export var b = "b"; // main.js console.log(a); // "a" variable is not available in a global scope import {b} from "lib"; console.log(a); // is "a" variable available in a global scope or only in a module scope?
Can I use "a" variable in a global scope after module importing or is it available only in a module scope? Will ES6 modules have a similar working principle like this trick:
// module exports.module1 = (function(){ var a = "a"; })(); // "a" variable is not available in a global scope
The block scope restricts a variable's access to the block in which it is declared. The var keyword assigns a function scope to the variable. Unlike the var keyword, the let keyword allows the script to restrict access to the variable to the nearest enclosing block.
"Scope" refers to the ability of a variable or named module to be seen by calling code. For example, two modules may both declare a variable named "X".
Module scope In modules, a variable declared outside any function is hidden and not available to other modules unless it is explicitly exported. Exporting makes a function or object available to other modules. In the next example, I export a function from the sequence. js module file: // in sequence.
ES6 comes to your rescue with the concept of Modules. A module organizes a related set of JavaScript code. A module can contain variables and functions. A module is nothing more than a chunk of JavaScript code written in a file. By default, variables and functions of a module are not available for use.
Can I use "a" variable in a global scope after module importing or is it available only in a module scope?
It's only available inside the module it was declared in.
Will ES6 modules have a similar working principle like this trick: [...]
Basically yes.
ES6 has these kinds of scopes, order from "top" to "bottom":
You can do globalThis.a = "a"
and access it after that module has loaded. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With