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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.