Pass By Value vs Reference! What’s the default really?

Source Code Scout
3 min readMar 16, 2022

So this Pass By Value vs Pass By Reference is really a big confusing part of day to day programming. And when you get into some Functional Programming-oriented environments like ReactJS, this thing just tops the list of annoying things.

In this article I am going to try to explain what exactly is the default and what to take care of.

First of all, Almost Everything Is PASS-BY-VALUE By Default. now, that’s a bold statement. But let’s get our hands a little bit dirty here…

Example 1

In the above example, the function changeArr doesn't change the actual value of variable a, which means that this an example of Pass-By-Value.

What is actually happening is that for the execution context of function changeArr, the compiler is creating a copy of the variable and doing all the operations which we want on that copied variable only. This is what, in fancy words, called Pass-By-Value.

Now let’s change the course of our experiments a little bit…

Example 2

The above is a bit confusing. Now the function changeArr is ending up making changes in the actual variable and all the things that I said above have stopped making sense. From this, we can draw a conclusion that for Arrays, (a non-primitive data type) the default behavior is Pass-By-Reference. This conclusion is still wrong. See why-

Example 3

When we re-assign the array, it again shows Pass-By-Value behavior.

The default behavior is still Pass-By-Value (as we can see above). But, what we are actually passing has changed. Passing a primitive like a number is different from passing non-primitive like an Array. What we are actually passing here, the variable a, is called an Object Reference. When we pass an object reference, it is actually copied like we do in Pass-By-Value. But when we modify it in line number 3 of example 2, we are actually looking up using that value, and doing the changes in the Heap on the location which we got from the Object Ref. This means that we are not actually changing the value of what was passed here, but of something which we were pointed to. Which is why, it modified the actual value (but not really) in Example 2 but not in Example 3.

So in future if you want to change the actual value, don’t re-assign the variable, and still if you don’t have any other option, return that value from that function and assign it to the actual variable while invoking the function.

I have for the convenience of the masses used JavaScript in this blog. You can find same examples in Java, C++ and Python here.

This brings us to the end of the article or story (as Medium likes to call it). Thanks for reading all the jargon that I just wrote. Like Share Follow for more.

--

--