Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 module scope

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 
like image 505
Kirill A. Khalitov Avatar asked May 17 '15 14:05

Kirill A. Khalitov


People also ask

What is scope in ES6?

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.

What is module scope?

"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".

What is module scope in JS?

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.

What is a module in ES6?

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.


2 Answers

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":

  • Global scope
  • Module scope
  • Function scope
  • Block scope
like image 151
Felix Kling Avatar answered Nov 04 '22 20:11

Felix Kling


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

like image 37
Joakim L. Christiansen Avatar answered Nov 04 '22 20:11

Joakim L. Christiansen