@ngrx Angular RxJS Testing

Javascript Arrays – passing by reference or by value?

I stumbled across a great article about javascript arrays – Mastering Javascript Arrays.

One fact that i didn’t realize until reading this article is that if you pass an array to a function – it is passed by reference by default. Actually, any non primitive object is passed by reference.


Array By Reference

Basically it means that if you make any changes to the array inside the function, these changes are saved in the original array so you don’t have to “return myArray” at the end of this function (or at any other return statement inside this function) – that’s what’s so great about javascript – being dynamic enough and consolidate various tricks from other low-level languages.

At this point, I also realized the benefit of creating an array from a dom collection query – i.e. – document.getElementsByTagName(‘div’) – and as nicholas zakas pointed out in his javascript optimizations presentation he gave at google tech talk youtube channel (bullet 8). I also noticed that jquery uses this concept to return a jquery object after querying the dom (and also with other operations). Jquery also has a utility “$.makeArray” to convert any object/array to a real array. One of the benefits of converting a dom collection to a regular array is boosting javascript performance when doing various operations on these elements.

Array By Value

In contrary, array can also be passed by value – a copy of the array is passed- which means that changes that made to the passed array won’t be saved in the original array. This can be done by using the native array method – “slice()” – as described in any javascript language reference. The ‘slice’ method in this case will return a shallow copy of the array.