pointers and pass by reference in javascript
• javascript
An explanation of how Javascript efficiently passes large data.
Where are the pointers?
When I first started using Javascript I noticed that it lacked a pointer data type. Coming from other languages, I wondered how Javascript passed large data types like objects and arrays. So I did some experimentation and discovered that whenever an object is stored to a variable, that variable becomes a pointer to the object instead of the object itself.
Here’s an example:
var pointer1 = {a: 1};
var pointer2 = pointer1;
pointer2.a++;
console.log(pointer1, pointer2); // both are now {a: 2}
Note that when either variable pointer1 or pointer2 change, the shared object they point to in memory changes.
Passing Arrays
Because variables for objects and arrays (which are really just objects in Javascript) are all pointers. When passing an array into a function, the function will have a pointer to the original array. This means any changes to the array within the function will also change the array outside the function.
Example:
var arr1 = [1, 2, 3];
var func = function(arr2) {
for(var i = 0; i < arr2.length; i++) {
arr2[i]++;
}
};
func(arr1);
console.log(arr1); // [2, 3, 4]
Note that the original array is modified instead of a copy of the array being made within the function. To avoid modifying the original array, a copy of the array should be made before any modifications:
var arr1 = [1, 2, 3];
var func = function(arr2) {
arr = arr2.slice();
for(var i = 0; i < arr2.length; i++) {
arr2[i]++;
}
return arr2;
};
console.log(func(arr1)); // [2, 3, 4]
console.log(arr1); // [1, 2, 3]
Here the array is copied using the slice() function so the original array stayes the same.
One last example
Here’s one last example that shows some of the interesting things that can be done with pointers:
var obj = {value: null};
obj.value = obj;
console.log(obj); // {value: {value: {value: ...}}} and so on
In this case the property value in obj contains a pointer to it’s own object which means when attempting to log it the nested objects never end.