An immutable object is an object whose state cannot be modified after it is created.
Object.observe(obj, fn);
Basic aspects of concurrency
Javascript is executed asynchronously,
but still in a single-thread
Sorting a list
// shared state
let animals = [ 'hamster', 'cat', 'mouse', 'dog' ];
let sortedAnimals = animals.sort();
console.log(_.isEqual(animals, [ 'hamster', 'cat', 'mouse', 'dog' ]));
// false, why ?
console.log(animals === sortedAnimals);
// true, why ?
Event Listerns etc. triggered while modifying shared state
// some global & shared state
let data = [ 1, 2, 3, 4 ];
let sum = 0;
...
listener.onMessage = (event) => { // some async code
for (let index = 0; index < data.length; index++) {
sum += data[index];
}
}
// listener2-N ...
...
console.log(sum === 10); // true, but always true ?
Use "value" instead of "object", because ...
let animal = {
name: "Homer",
age: 2,
type: "hamster",
legs: 4
};
let shallowCopy = Object.assign({}, animal);
console.log(animal === shallowCopy); // false
let animals = [ 'hamster', 'cat', 'mouse', 'dog' ];
let shallowCopy = [].concat(animals);
console.log(animals === shallowCopy); // false
let animal = {
name: "Homer",
age: 2,
type: "hamster",
legs: 4
};
let shallowCopy = { ...animal };
console.log(animal === shallowCopy); // false
let animals = [ 'hamster', 'cat', 'mouse', 'dog' ];
let shallowCopy = [ ...animals ];
console.log(animals === shallowCopy); // false
Enable and simplify immutability in Javascript
Simplify handling of immutable state
e.g. reducers/reductions in Redux
Simplify handling of immutable state
in a structured & consistent way
Immutable.js, Immer.js and Redux focus on different aspects of immutability