---
# System prepended metadata

title: What Are The Differences Between Call by Reference/Value/Sharing?
tags: [Javascript]

---

# What Are The Differences Between Call by Reference/Value/Sharing?
###### tags: `Javascript`

## Datatypes
In Javascript, There are eight datatypes: 

| Datatype  | Description                                        | Example                            |
|:-:|:- |:- |
|  String   | represents textual data| ```'hello' "hello world"``` etc|
|  Number   | an integer or a floating-point numb| ```3``` ```3.234``` ```3e-2``` etc |
|  BigInt   | an integer with arbitrary precision| ```30404051n``` ```1n```etc        |
|Boolean| Any of two values: true or false    | ```true``` and```false```|
|Undefined|a data type whose variable is not initialized|```let a;```|
|Null|denotes a null value| ```let a = null;```|
|Symbol|data type whose instances are unique and immutable|```let value = Symbol('hello');```|
|Object| key-value pairs of collection of data|```let student = { };```|

The first seven datatypes are "Primitive" and the last one(object) is "Object" type. The date in "Primitives" type only exist in the form of value. However, the "Object" may be a combination of 0 or various data types such as values or objects. 

Primitives:
* String 
* Number
* BigInt
* Boolean
* Undefined
* Null
* Symbol (Defined after ECMAScript 6)

Object:
* Object

## Call(Pass) by Value

When a variable of primitive type```a```is  declared and assigned with a value, ```a``` will also creates a memory space(assuming 0x001) to storage the value. Now if another primitive variable ```b``` is declared and ```b = a```, then ```b``` will also create a new memory space(assuming 0x002) and storage the copy value of ```a```. In this case, ```a``` and ```b```have different memory spaces and they don't affect each other. That is if one of them changes the value, the other one will stay unchange. 
![Pic for call by value](https://i.imgur.com/lqVKVvh.png)

Now, let's see a example
```javascript=
var a = 10;
var b = a;

console.log( a );   // 10
console.log( b );   // 10

a = 100;

console.log( a );   // 100
console.log( b );   // 10
```
The result shows that ```a``` and ```b```have different memory space. In other words, the value of ```b``` is just a copy of  ```a```. As a result, value of ```b``` stay unchange after we reassigned ```a```.***And in Javascript, primitive types are pass by value.**

Fun Fact
```javascript=
function swap(a, b) 
  var temp = a;
  a = b;
  b = temp;
}

var x = 10;
var y = 20;
swap(x, y);
console.log(x, y) // 10, 20
```
Sometime we want to swap the values of ```x``` and ```y``` but it just doesn't work(see example). This is bacause ```x``` and ```y``` are primituve type and pass by value, abd the ```x``` and ```y``` we put in to ```swap()```are the copies of them instead of the real of them. So, the result of ```console.log(x, y)``` are actually the values ```x``` and ```y``` at rows 7 and 8. 

What if we want to successfully swap them? Here, we just need to put the ```console.log(x, y)``` inside the function like this:
```javascript=
function swap(a, b) {
    var temp = a;
    a = b;
    b = temp;
    console.log(a, b);
  }
  
var x = 10;
var y = 20;
swap(x, y)// 20 10
```
or there are some other ways you can goole and give them a try:
* Using a Temporary Variable
* Using ES6(ES2015) Destructuring assignment
* Using Arithmetic Operators
* Using Bitwise XOR operator

## Call(Pass) by Reference
When we declare a object ```c```, it also creates a memory space(assuming 0x003) to storage the data inside the object. But unlike the previous case, if we declare another object ```d``` and assign```d = c```, ```d``` will piont to the same object and sharing the same memory space(0x003). In this case, every change on ```c``` will also make effect on ```d```.  
![call by reference](https://i.imgur.com/eX986so.png)

let's see a example:
```javascript=
// by reference (all objects (including functions))
var c = {greeting : 'Hello'};
var d;
d = c;

console.log(c);//{greeting: 'Hello'}
console.log(d);//{greeting: 'Hello'}

c.greeting = "Hola";

console.log(c);//{greeting: 'Hola'}
console.log(d);//{greeting: 'Hola'}

// by reference (even as parameters)
function changeGreeting(obj){
  obj.greeting = 'Hi'; //mutate
}

changeGreeting(d);
console.log(c);//{greeting: 'Hi'}
console.log(d);//{greeting: 'Hi'}
```
We declared two object ```c``` and ```d```, and assigned ```d = c```. We can see that once we reassigned the value in inside ```c```(row9), ```d```also changed(row12).  And we addtionally change ```d```again with a function(row15), ```c```also changed(row20). The result above tells us that ```c``` and ```d``` are call by reference since they are object type. Thus, we know ***Object type are call by reference, and object type includes ```function``` ```array``` and ```object```**.

## The Third Definition(Call(Pass) By Sharing)
Now if we modify the code from previous paragraph, we see:
```javascript=
var c = {greeting : 'Hello'};
var d;
d = c;
console.log(c);//{greeting: 'Hello'}
console.log(d);//{greeting: 'Hello'}

c = {greeting: "Hola"};
console.log(c);//{greeting: 'Hola'}
console.log(d);//{greeting: 'Hello'}
```
We reassigned ```c``` with object literal method, and ```d```didn't change. Why????
Let's see another example:
```javascript=
var c = { greeting: "Hello" };

function changeGreeting(obj) {
  obj = { greeting: "Hi" };
}

changeGreeting(c);
console.log(c);   //  { greeting: "Hello"}
```
Base on call by reference, the parameter ```obj``` should have same memory space same as object```c``` which will be reassigned in side the function and eventually results ```{ greeting: "Hi" }```, rigth? But we are wrong, the result is  ```{ greeting: "Hello" }```. Why is that????

It's simple, the keypoint if these two examples is the reassign of the the object. As long as a object is reassigned with a new whole object instead of only changing the value inside the object, a new memory space will be created and pointed by the new object. That is, once the case above happenes, the way to transport date will be converted from call by reference to call by value. That's why wee see a result similar to call by value. 

Since Javascipt has this kind of special situation, some people consider Javascript is call by sharing. But nevertheless, the whole idea is constructed by call by value and call by reference. We just need to remeber that primitives type is call by value and object type is call by reference in general respectively. Beside, what makes them so confusing is that there is no identical definition to them on different language.

## Comparison
Addtionally, if you are still confused, you can compare them to check the strict equility. 
```javascript=
var arrRef = ['Hi!'];
var arrRef2 = arrRef;
console.log(arrRef === arrRef2);  //  true
```
The example above results true because call by reference.

Another one
```javascript=
var arrRef1 = ['Hi!'];
var arrRef2 = ['Hi!'];
console.log(arrRef1 === arrRef2);  //  false
```
Different reference, so result is false

One more
```javascript=
var a = 'Kuro';
var b = 'Kuro';
var c = 'Jack';

console.log( a === b );      // true
console.log( a === c );      // false
```
Different from last one, primitive type check the value instead of the reference, so ```a === b``` is true and ```a === c```  is false obviously.
## Reference
* https://pjchender.blogspot.com/2016/03/javascriptby-referenceby-value.html
* https://ithelp.ithome.com.tw/articles/10191057
* https://blog.techbridge.cc/2018/06/23/javascript-call-by-value-or-reference/
* https://medium.com/@mengchiang000/js%E5%9F%BA%E6%9C%AC%E8%A7%80%E5%BF%B5-call-by-value-%E9%82%84%E6%98%AFreference-%E5%8F%88%E6%88%96%E6%98%AF-sharing-22a87ca478fc