28
loading...
This website collects cookies to deliver better user experience
// Shared state
const x = {
val: 2
};
// Mutates shared state
const x1 = () => x.val += 1;
// Mutates shared state
const x2 = () => x.val *= 2;
x1();
x2();
console.log(x.val); // 6
// This example is exactly equivalent to the above, except...
const y = {
val: 2
};
const y1 = () => y.val += 1;
const y2 = () => y.val *= 2;
// ...the order of the function calls is reversed...
y2();
y1();
// ... which changes the resulting value:
console.log(y.val); // 5
const x = {
val: 2
};
const inc = x => ({...x, val: x.val + 1});
const double = x => ({...x, val: x.val * 2});
console.log(inc(double(x)).val); // 5
const y = {
val: 2
};
/*
Because the functions don't mutate, you can call
these functions as many times as you want, in any order,
without changing the result of other function calls.
*/
// These calls do nothing:
inc(y);
double(y);
console.log(inc(double(y)).val); // 5