Problem with: pass by reference

var test = [10, 20, 30];
(function()
{
var testFunc = function(myVar)
{
myVar[4] = 10; // works
myVar.push(10); // works
myVar = [1, 8]; // fails
};
testFunc(test);
})();
console.log('test:');
console.log(test);


As you can see, assigning a new array to the variable that was passed by reference will not work correctly. Javascript works so weird. Changing the "passed by reference variable" works. But assigning a new type to it (which should also be passable by reference) does not...
That's to be expected. "myVar" is a pointer, that references the given variable. You can access that variable directly via the pointer, but on your last line, you assign a different value to "myVar", so it doesn't point to the given variable, anymore.


I suggest you to read a bit about how passing by reference (and value) works. Also note, that primitive variables (like numbers and, i think, strings) are passed by value. This is called "pass by reference by value" or "call by sharing": https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing
So it's a call-by-sharing. Not a call-by-reference.


Yeah I know about primitive types being passed by value. Though, I read that strings are also passed by reference (which is weird but okay).


Normally (C++, C#, etc.) when I change the value of a pass-by-reference-variable, it will change where-ever it is pointing to. Not the address itself (unless you use the & operator). But in Javascript it's called pass-by-sharing and for some epic reason it does not support assignments...

Original thread: https://forums.rpgmakerweb.com/threads/problem-with-pass-by-reference.56555/