Skip to content

Instantly share code, notes, and snippets.

@mikegerwitz
Created March 22, 2011 05:23
Show Gist options
  • Save mikegerwitz/880820 to your computer and use it in GitHub Desktop.
Save mikegerwitz/880820 to your computer and use it in GitHub Desktop.
By reference vs by value
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