From what I can tell, an import binding is immutable
import { foo } from './foo';
...
foo.bar = 23; // works
...
foo = { bar: 23 }; // syntax error
However, I've read elsewhere that JS imports are actually non-writable (not immutable)...in which case wouldn't the first assignment statement, foo.bar = 23;
also throw a syntax error?
UPDATE (how I understand it now)
...to paraphrase the excellent answer by @FelixKing...
JS imports are immutable bindings to the exported thing (variable, function, etc).
For non-primitive imports, this does not mean the properties on the imported object are necessarily immutable or non-writable.
The import statement makes modular code possible in JavaScript (and also, code reuse and sharing). Without import or a similar mechanism, a developer could only write a JavaScript program as a single program in one file.
So the answer is no, it does not create a copy of the exports. The module is initialised once and each import will receive a reference to the same value.
Using ImmutableJS can improve dramatically the performance of your application. And, because the immutable data never changes, you can always expect new data to be passed from the above. To make sure you are correctly comparing the data and not updating the UI when there is no change, you should always use the .
An immutable value is one whose content cannot be changed without creating an entirely new value. In JavaScript, primitive values are immutable — once a primitive value is created, it cannot be changed, although the variable that holds it may be reassigned another value.
in which case wouldn't the first assignment statement, foo.bar = 23; also throw a syntax error?
Non-writable refers to the value of the variable, where as mutable (immutable) describes whether the value itself can be changed in place or not.
Imports are not writable as you have found out. But if the value of an import is mutable then you can update the value (in place).
foo.bar = 23;
does not assign a new value to foo
. It is reading the value of foo
and then modifying it (by adding or overwriting a property). If you did
var oldFoo = foo;
foo.bar = 23;
oldFoo === foo; // true
you would get true
. That indicates that foo
has still the same value assigned to it. It only updated the value (an object) in place.
All objects are mutable (unless passed to Object.freeze
or similar functions), whereas primitive values (String, Number, etc) are all immutable.
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