Javascript by value vs by reference

Intermediate developers like me get confused when debugging code and face some wired bugs. It happens because javascript is not like other programming language. It works bit differently.

Let’s examine a problem.

We want to make a copy of this array and make change in new copy like this.

So why old “peoples” array also been changed ? Let’s understand by value and by reference.

By value

Suppose a and b are variables. a = 5, then we set b = a. What will happen ?

First a creates new memory space in computer that holds the value 5. Then b creates another memory space for value 5. b is simply copy of a. They both have different existence in memory by value.

Take a look at this figure.

by value vs by reference

All primitives(string, number, boolean, symbol, undefined, null) are saved in memory by value.
Making change of a or b won’t affect another.

Pretty simple concept. But collections are not saved by value they are saved by reference. Let’s explain this,

By reference

Suppose we have an object

a creates new memory space in computer.

Now we set the a = b, b is another newly created variable. At this moment b won’t create or copy a new memory space. It just points to that object.

by value vs by reference

So making change in a or b will affect both a and b. Because they are the same object. Computer memory has only one memory space for both a and b.

Makes sense ?

If you want to add anything feel free to comment. Thanks for reading.

MH Rafi

Full stack Javascript developer at ThemEgret