# By value, by reference in javascript

## The pass by reference mechanism in javascript

Lately I have realized some useful facts about the pass by reference mechanism in javascript.
Let me share them here.

To cut to the chase, there is no such thing as passing a variable as reference in javascript. Variables are always passed as values in arguments. This means that what you can do in PHP for example when you do `function test(&\$val){}` is not possible in javascript, there is no special keyword or symbol to do that.

However, there are some cases when you can “simulate” this behaviour in javascript. But before showing you how to do that, let’s make a recap.

What is passing a variable by reference?

Passing a variable by reference means that when you pass a variable as an argument to a function, what is passed as an argument is the reference in memory to that variable. So what the function body manipulates is the reference to that variable, it means when it writes to that reference, the original variable is modified. In other words, the variable passed by reference is accessible in the function body, and any modification to its reference inside the function body, also modifies it. This example in PHP illustrates it:

```\$a = 2;

function test(&\$b){
\$b = 3;
}

test(\$a);

// \$a = 3
```

In some situations this comes in really handy. For example, if you need an array that is constantly up to date, for example because you need it always sorted, you can pass it as a reference to the function that modifies it. This way wherever you use this array in the code, it will reflect those changes without any need to rebuild it at every change.

With javascript though, such thing is not possible. From last example :

```var a = 2;

function test(a){
a = 3;
}

test(a);

// a = 2, it was not modified
```

Recently I needed the pass by reference behaviour from javascript because I was building a Binary Search Tree. BSTs are another use case that work well with pass by reference. When you add or remove elements it is very practical to not rebuild the whole tree but just change the parts that need to be modified, passing the tree as a reference makes that happen. I discovered some interesting facts in javascript when you try to do that.

How to do that in JavaScript?

I discovered 2 things:

1. You can only simulate the pass by reference mechanism on arrays and object variables, meaning variables you write like [ ] or like { }. So forget trying to do that on Strings, Numbers and other types.

The way you would do in javascript is to pass the reference of the object or array as value to the function, and from there the function can modify the reference and in consequence the object or array.

When you write `var a = [1, 2, 3];` `a` is a reference to the array `[1, 2, 3]`. This means that if you do ` var b = a;` ` b `is also a reference to the same array. And doing `a.push(4)`, will alter the original array, and also modify `b`. So `a` and `b` are just references. For objects it works the same. This means that if you pass the reference to the array as argument, the original array will be accessible. Doing this will modify the original array from the function’s body :

```var a = [1, 2, 3];

function alterArray(b){

//b is a reference to original array
b.push(4);

}

alterArray(a);

//a = [1, 2, 3, 4]
```

This frees you from doing :

```var a = [1, 2, 3];

a = alterArray(a);

function alterArray(b){

//some actions on b

return b;

}

```

Try these examples :

With an object it works the same:

In other words, passing the reference of an array or object to a function gives the function’s body access to the contents of the variable being referred to. You can always alter the content of the original array or object in the function’s body through their reference in the arguments. However here is the other discovery :

2. You can only alter the values and properties in the array or object. You can’t override the value of the array or object itself.

Consider these examples:

The reason being that what you pass as argument is a reference as a value, so it means if you change the value of this reference, it will just refer to something else but it will in no way affect the variable it was referring to before. In a normal pass by reference, you would be able to override the value of the variable being referred to.

You can remember it this way: By value, by reference in javascript By value, by reference in javascript

So now you know the scope of what’s possible in javascript when you need the pass by reference mechanism :

You can only alter values or properties in arrays or objects.
{"ft_lang_label":"__label__en","ft_lang_prob":0.8965012,"math_prob":0.77444696,"size":4425,"snap":"2019-51-2020-05","text_gpt3_token_len":994,"char_repetition_ratio":0.16308528,"word_repetition_ratio":0.030487806,"special_character_ratio":0.23480226,"punctuation_ratio":0.114503816,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9620403,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,5,null,5,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-01-19T11:17:45Z\",\"WARC-Record-ID\":\"<urn:uuid:1f6e7389-26d5-4178-be25-dcf6f6ea09e1>\",\"Content-Length\":\"91307\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:9eb173f8-f227-4b53-bf9e-1516f83b2c97>\",\"WARC-Concurrent-To\":\"<urn:uuid:cbffef8e-01a5-469e-8dd5-edeede2da6c1>\",\"WARC-IP-Address\":\"213.186.33.40\",\"WARC-Target-URI\":\"https://machinesaredigging.com/2014/05/01/by-value-by-reference-in-javascript/\",\"WARC-Payload-Digest\":\"sha1:TNMK7TX3L6AQDA3OBEPCURG65PIIMCHG\",\"WARC-Block-Digest\":\"sha1:QIFSVKA65YBIDFUAFKRSKUDZNM6V5HVH\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-05/CC-MAIN-2020-05_segments_1579250594391.21_warc_CC-MAIN-20200119093733-20200119121733-00043.warc.gz\"}"}