Function params pass Objects by reference, but..
I was doing this problem in javascript:
To write a function which can convert an array like [1,2,3] to a linked list style of data structure like:
{ value: 1,
rest:
{ value: 2,
rest:
{ value: 3,
rest: null
}
}
}
And vice-versa - which can take a object like above and convert it into an array.
While doing the second problem: this is what I wrote:
function listToArray(list) {
const array = [];
while (list) {
array.push(list.value);
list = list.rest;
}
return array;
}
In Line number 5
list = list.rest;
I though about it for a minute and this is a slightly tricky line - because we all know that arrays and objects in javascript are passed by reference and the though lingered in my head for a second that won't it change the original list to list.rest.
But then it dawned upon me, list is a variable or a binding to that object and if I try to mutate that object by using the list variable like this:
list.x = "Prabhas"
then it will surely mutate that object - but if i try to assign something new to the "list" variable - then that doesn't really care about the object being passed by reference - and I was planning to create a deep copy of the list object and store it in a new variable - but I avoided that.
And yes the function works as expected.
You might wonder about why I choose the image of an octopus for this article - it's because of this analogy about the tentacles of an octopus trying to be bindings to various values in js.