I am confused as to how JavaScript decides what is passed by value and reference, so I attempted to figure it out by writing some tests. The results have confused me further. Can anyone explain how the interpreter decided if variables were passed by val/ref in this code? Also, do you know how to explicitly pass a variable by reference?
function test(str, obj1, obj2, arr1, arr2) {
str = "Str was passed by reference!";
obj1.val = "Obj1 was passed by reference!";
obj2 = {val: "Obj2 was passed by reference!"};
arr1[0] = 'r';
arr1[1] = 'e';
arr1[2] = 'f';
arr2 = "arr2 was passed by reference!".split('');
}
var str = "Str was passed by value!";
var obj1 = {val: "obj1 was passed by value!"};
var obj2 = {val: "obj2 was passed by value!"}
var arr1 = ['val'];
var arr2 = "arr2 was passed by value!".split('');
test(str, obj1, obj2, arr1, arr2);
console.log(str);
console.log(obj1);
console.log(obj2);
console.log('arr1 was passed by ' + arr1.join(''));
console.log(arr2.join(''));
This code logs:
Str was passed by value!
Object {val: "Obj1 was passed by reference!"}
Object {val: "obj2 was passed by value!"}
arr1 was passed by ref
arr2 was passed by value!
Thanks :)
I have this code on JSFiddle if you would like to see it yoursef.
--edit--
For context, I originally was trying to explicitly pass in large objects / primitives by reference.