Is it true that in JavaScript functions return objects other than Boolean and Numbers by reference?
How is this possible when those objects are destroyed when the function they belong to terminates?
Is it true that in JavaScript functions return objects other than Boolean and Numbers by reference?
How is this possible when those objects are destroyed when the function they belong to terminates?
Objects are not destroyed until all references to them are gone and garbage collected. When the object is returned, the calling code gains a reference to it, and the object is not garbage collected.
Technically, the called function's stack frame is destroyed when it returns. The object, however, is not on the stack, but on the heap. The function's local reference to the object is on the stack, and is therefore destroyed, but the calling code's reference isn't destroyed until some time later.
As a side note, it isn't really important how it is returned, because the function can't use the object anyway after it returns.
Is it true that in JavaScript functions return objects other than Boolean and Numbers by reference?
It is true, objects in JavaScript are always passed by reference
How is it possible when those objects destroyed when the function those belong to terminates?
Only references are destroyed, not the values itself. And as long as there are no references left, the object is a candidate to be garbage-collected.
Two great answers there, but just thought I should add that it's easy enough to test:
function modify(arg) {
arg.modified = true;
}
test = 4;
modify(test);
console.log(test.modified); // undefined
test = {};
modify(test);
console.log(test.modified); // true
test = "";
modify(test);
console.log(test.modified); // undefined
where undefined means it has been copied instead of being passed by reference. Note that strings aren't passed by reference either.
Arguments (including objects) are sent to a function by value. Properties of an argument object are available and changeable that is behaves like references. Look at the example below:
function changeObj(obj){obj.a *= 10; return true;}
function killObj(obj){obj = null; return true;}
function changeAndKillObj(obj){obj.a += 1; obj = null; return true;}
var a = {a:1, b:'test'};
console.log(a); //Object {a:1, b:'test'}
changeObj(a);
console.log(a); //Object {a:10, b:'test'}
killObj(a);
console.log(a); //Object {a:10, b:'test'}
changeAndKillObj(a); //Object {a:11, b:'test'}
Bottom line: You can do whatever you want with object's properties but not with the object itself. Any assignment to the argument makes it different object and unlink from initial object.
object is an address of (reference to) it. This value is immutable.