Created
March 22, 2011 05:23
-
-
Save mikegerwitz/880820 to your computer and use it in GitHub Desktop.
By reference vs by value
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
var a = {}, | |
b = {}; | |
// primitives are passed by value | |
a.num = 1; | |
b.num = a.num; | |
b.num = 5; | |
a.num; // still equals 1 | |
b.num; // equals 5 | |
// objects are passed by reference | |
a.foo = [ 1, 2, 3 ]; | |
b.foo = a.foo; | |
b.foo[ 0 ] = 'bar'; | |
a.foo; // [ 'bar', 2, 3 ] | |
b.foo; // [ 'bar', 2, 3 ] | |
// reassigning the property only changes the reference on THAT object | |
b.foo = {}; | |
a.foo; // [ 'bar', 2, 3 ] | |
// deleting only removes the reference on that object | |
delete b.foo; | |
b.foo; // undefined | |
a.foo; // [ 'bar', 2, 3 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment