Created
July 12, 2011 19:27
-
-
Save jmarca/1078768 to your computer and use it in GitHub Desktop.
javascript assignment exploration
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
// assignment as copy or reference? | |
// run in node.js as node copyorref.js | |
console.log('assignment by value for simple scalars') | |
var a = 8; | |
var b = a; | |
a++; | |
console.log('a: '+a + ', b (not changed): '+b); | |
console.log('\nassignment by reference: aa[4]=45 is also in other vars') | |
var aa = [1,2,3]; | |
var bb = aa; // reference | |
var x = {'aa':aa}; // this is also a ref to aa | |
var y=x //ref; | |
aa[4]=45; | |
console.log('aa: '+JSON.stringify(aa)) | |
console.log('bb: '+JSON.stringify(bb)) | |
console.log('x: '+JSON.stringify(x)) | |
console.log('y: '+JSON.stringify(y)) | |
console.log('\nbut if you change aa by assignment, bb and refs in x,y don\'t change') | |
aa = aa.slice(1); | |
console.log('aa: '+JSON.stringify(aa)) | |
console.log('bb: '+JSON.stringify(bb)) | |
console.log('x: '+JSON.stringify(x)) | |
console.log('y: '+JSON.stringify(y)) | |
console.log('\nput a ref to the new aa into x and change other things, all mirrored by y (same reference)') | |
x.aa=aa; | |
x.banana = 'fruit'; | |
y.bb = bb; | |
aa[4]=4; | |
bb[4] = 45; | |
console.log('aa: '+JSON.stringify(aa)) | |
console.log('bb: '+JSON.stringify(bb)) | |
console.log('x: '+JSON.stringify(x)) | |
console.log('y: '+JSON.stringify(y)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment