Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are JS imports immutable or non-writable?

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.

like image 431
sfletche Avatar asked Mar 29 '17 13:03

sfletche


People also ask

What are imports in JavaScript?

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.

Does importing create a copy?

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.

Should I use immutable JS?

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 .

What is immutable object in JS?

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.


1 Answers

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.

like image 75
Felix Kling Avatar answered Sep 28 '22 02:09

Felix Kling