LUH3417 LUH3417 - 3 months ago 6
Javascript Question

Are import values disconnected from their export values still read-only?

Given is the following module structure:

// module A:
export let a = 1; // named export
export function inc() { a++; } // named export

// module B:
let b = 1;
export default b; // default export (equivalent to `export default 1`)
export function inc() { b++; } // named export

// module C:
let c = {};
export default c; // default export

// module E:
import a, {inc as incA} from "./A";
import b, {inc as incB} from "./B";
import c from "./C";

incA();
console.log(a); // logs 2, because "a" has a live connection to the export value
a++; // Error (because a is a live read-only view on the export)

incB();
console.log(b); // logs 1, because "b" is disconnected from the export value
b++; // Does this throw an error as well?

c.prop = true; // I think mutations are always allowed, right?
c = {}; // but are reassignment allowed too?


If I have a default export of an expression (
export default b
or
export default 1
) a corresponding import is disconnected from this export value. Considering this, is such an import still read-only that is, can I reassign
a
or
c
?

Answer

Import bindings are always read-only, see the abstract CreateImportBinding operation in the spec, step 5:

  1. Create an immutable indirect binding in envRec for N that references M and N2 as its target binding and record that the binding is initialized.

(my emphasis)

That operation is used by ModuleDeclarationInstantiation when processing the import entries of the module.

So:

b++; // Does this throw an error as well?

Yes, b is read-only.

c.prop = true; // I think mutations are always allowed, right?

Provided the exported object allows it, yes.

c = {}; // but are reassignment allowed too?

No, c is read-only.

Comments