Last active
August 29, 2015 14:16
-
-
Save awilson28/8278a1892b1477c86998 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
Primitives are stored as copies | |
*/ | |
//declare and initialize a variable | |
var string = 'string'; | |
//we copy the variable's value into a new variable | |
var hood = string; | |
//check that they are the same | |
console.log(hood === string) //true | |
//modify the value of the first variable | |
string = 'new string'; | |
//the copy does not change | |
console.log(hood) //'string' | |
console.log(string) // 'new string' | |
/* | |
Objects are stored as references | |
*/ | |
//initialize a variable to refer/point to an array | |
var a = [1, 2, 3]; | |
//share the reference with another variable; there is only one array in memory | |
//we simply create a second pointer to this single array and call it b | |
var b = a; | |
//check that they are the same | |
console.log(b === a) // true | |
//modify the array using the original reference | |
a[0] = 99; | |
// display the changed array [99, 2, 3] using the new reference | |
console.log(a) // [99, 2, 3] | |
console.log(b) // [99, 2, 3] | |
/* What happened? | |
Here we mutated the object a; we did not REBIND the object a which is why a and b still point to the same object | |
When we change the properties of an object, we mutate the object | |
Mutating the object does not change the links between the pointers and the object | |
*/ | |
//initialize a variable to refer/point to an array | |
var a = [1, 2, 3]; | |
//copy the reference into another variable | |
var b = a; | |
//check that they are the same | |
console.log(b === a) // true | |
//modify the array using the original reference | |
a = [504, 345]; | |
console.log(b === a) //false | |
// display the changed array using the new reference | |
console.log(a) // [504, 345] | |
//b still points to the original array value; b is not affected by a's reassignment | |
console.log(b) // [1, 2, 3] | |
/* | |
What happened here? | |
We rebound/reassigned the pointer a to an entirely new array | |
Rebinding a means that the link between a and [1, 2, 3] has been severed | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment