Problem with: pass by reference

SilverDash

Veteran
Veteran
Joined
Oct 11, 2015
Messages
426
Reaction score
173
First Language
Dutch
Primarily Uses
RMMV
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...
 

Iavra

Veteran
Veteran
Joined
Apr 9, 2015
Messages
1,797
Reaction score
863
First Language
German
Primarily Uses
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
 

SilverDash

Veteran
Veteran
Joined
Oct 11, 2015
Messages
426
Reaction score
173
First Language
Dutch
Primarily Uses
RMMV
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...
 
Last edited by a moderator:

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

Latest Threads

Latest Posts

Latest Profile Posts

A part of me wants to return back to the beginning and first two chapters and remake them with parallax map. But I have decided not to. Every chapter is just another step in the journey. No need to walk back unless I have to revise dialouge.
Hey guys! Good news!
I just released the Games from Brazil - Part 2 on my Youtube Channel! I am really happy that part 1 had 100 views and I hope more people will be interested to see the potencial of Brazilian Game Devs!
Effervesce Fallacy™ - Attract Mode (proto)
Almost to the finish line!... or the starting... since it's just the demo. :kaomad2:

Forum statistics

Threads
107,570
Messages
1,030,634
Members
139,671
Latest member
WDRS
Top