A data structure that always returns a new value when the old one is getting modified.
Hence, the data structures are immutable.
//mutable
var a = 10;
a = 10 * 2
//immutable
const a = 10;
const b = a * 2;
var changeable = 1;
function bad (n, fn) {
changeable = changeable * 2;
return fn(changeable, n);
}
bad(1, multiply) // 2
bad(1, multiply) // 4
var changeable = 1;
function bad (n, fn) {
changeable = changeable * 2;
changeable = unknown(changeable);
return fn(changeable, n);
}
bad(1, multiply) //16
bad(1, multiply) // 253
- Same inputs, same output
- Every single time the function is being called
- Regardless of outside changes
Pssh, why do I need to care about that?
(why-is-this-important-ception)
- Guarantee the result is always what you expected
- No side effects
- Reduce #s of unit tests needed
- Fewer bugs
Declaring mutable variables in F#
let mutable name = "julia"
name <- "gulia"
Benefits of the "mutable" keyword
- Clearly indicate the variable is meant to be mutated
- Communicates the purpose of the variable
A data structure that always returns a new value when the old one is getting modified.
Hence, the data structures are immutable.
Modify the data
Only when the data can be mutated
Benefits of using immutable data
- Encapsulation is not as important (read-only data does not need to be hidden)
- No more locks! There is no shared mutable state. No race condition!
function randomPlus (n) {
return n + Math.random() * 100
}
Things that worked on Friday but no longer on Monday