Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning by reference in JavaScript?

Tags:

javascript

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?

like image 668
MTVS Avatar asked Jun 08 '12 23:06

MTVS


People also ask

Does JavaScript return by reference?

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.

What does it mean to return 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.

Is JavaScript pass by value or pass by reference?

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.

How do you make a reference in JavaScript?

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.


2 Answers

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.

like image 106
Kendall Frey Avatar answered Sep 21 '22 04:09

Kendall Frey


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.

like image 44
zerkms Avatar answered Sep 20 '22 04:09

zerkms