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?
In Pass by Reference, a function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.
It means you return by reference, which is, at least in this case, probably not desired. It basically means the returned value is an alias to whatever you returned from the function. Unless it's a persistent object it's illegal.
It's always pass by value, but for objects the value of the variable is a reference. Because of this, when you pass an object and change its members, those changes persist outside of the function. This makes it look like pass by reference.
The Bottom Line on JavaScript ReferencesOn variable assignment, the scalar primitive values (Number, String, Boolean, undefined, null, Symbol) are assigned-by-value and compound values are assigned-by-reference. The references in JavaScript only point at contained values and NOT at other variables, or references.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With