Created
May 17, 2017 01:34
-
-
Save abiodun0/1442f62dc6916c2a1421782654b0f2fc to your computer and use it in GitHub Desktop.
Immutability in javascript with numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // That’s a slightly different thing. Number in JS are always immutable already | |
| let a = 4; | |
| function getA() { | |
| return a++ | |
| } | |
| let v1 = getA() // v1 = 4 | |
| let v2 = getA() // v1 = 4, v2 = 5 | |
| let v3 = getA() // v1 = 4, v2 = 5, v3 = 6 | |
| // Because the value of the number doesn’t change in place. | |
| // By contrast: | |
| let ary = [] | |
| return getAry() { | |
| ary.push(ary.length) | |
| return ary | |
| } | |
| let v1 = getAry() // v1 = [0] | |
| let v2 = getAry() // v1 = [0,1], v2 = [0,1] | |
| let v3 = getAry() // v1 = [0,1,2], v2 = [0,1,2], v3 = [0,1,2] | |
| //but the fact that numbers might be immutable doesn’t mean the variable reference is. would be. | |
| // a is actually set to 5 after the first call but the operation returns the existing value before inc’ing it. | |
| // i’d say the lesson there is to rely on named functions | |
| // for transformation that are referentially transparent and idempotent | |
| let inc = (x)=> x + 1 | |
| // there’s a difference between a mutable variable and a mutable value. | |
| // Generally you want to avoid both, but mutable values are far worse than mutable variables. | |
| // A mutable variable can only damage its own lexical scope, | |
| // while a mutable value can poison a whole application. | |
| // mutable values are array situation | |
| // mutable variables are things without the const variable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment