By Value vs By Reference

Although this topic is not really that complicated, I will try my best to explain what by value and by reference means.

Let's take the first case.

In the beginning, let's say that we have the variable a and assigned some value (primitive type) to it. For example a number 10.

Together with this, we have the address of a variable in memory, after which we can refer to it.

The reference is really just an pointer to the location in memory.

Now if we create the second variable,nameit b, and set its value to equal a by doing b = a, although value will be the same (in our case since a is equal to 10, be will equal to 10 too), they will have two separate and reserved places in the memory.

Now another case.

At the start, create the object and assign it to the variable a. Then, like the above, set b = a.

In this case, another space in memory will not be reserved for that object. Now both variables will point to the same object. And since it is the same object in the same place in the memory, we can change that object using both variables.

For example if we started to look for a method, which is assigned to object a, we would find the same method attached to variable b.

Below is a little bit of code that I hope will clear everything up.

But before we go to the examples I would like to explain two concepts used in programming.


It simply means change something.


Means something can't be changed.

Ok, now examples.

In our code, we see several variables. Let's start as always from the first lines.

As you can see, we declared variable a and initialized b.

Then we set to b = a, after which we changed the value of variable a to 2.

What do we expect to see in this case after console.log of variable a and b?

This is due to the fact that, as mentioned above, although we have assigned to b, variable a, and what we have created, it is only a copy of it and each of them is located elsewhere in the memory.

By changing one, we do not influence the other in any way. After we attributed b = a. Each of them lives their own lives.

Then we're going to look at by reference.

The next variable is the variable c to which we assigned the object.

Now, as in the case of the variables a and b, we set the variable d to equal the variable c.

We are also changing them a bit here. Using c.greeting = "Hey" we change the value.

So what are we going to expect this time?

Here, as you see, it is quite different. As all variables indicate the same place in memory. A change using one variable affects the other.

A separate case is at the equality operator. Changing c will stop pointing to the same place in memory as variable d.

Next Post

I will continue to talk about objects, functions and the special 'this' variable.