I'm noticing behavior I don't understand in JavaScript. I understand that with regards to primitive types when passed to a function, they're passed by value. If we pass an object, they're passed by reference. What I wanted to do was shorten my code by encapsulating a repetitive section into a function; this function was to take a node object pointing to a node in a linked list, do something with its value, and then move it to the next node in the list. However that's not what happens. I've made a simple example here:
var testObj = {};
testObj.val = 5;
testObj.next = {
val: 7,
next: null
}
var temp = testObj;
console.log("Val before: ", temp.val); //prints 5
function test(node) {
console.log(node.val); //prints 5
node = node.next;
console.log(node.val); //prints 7
}
test(temp);
console.log("Val after: ", temp.val); //prints 5??
First I create a test node with a value and a next field pointing to the next node in the list which also has a value. I create another node which points to the first node in the list (this is common when you want to iterate through the list, you don't want to lose track of the root node.)
I'm confused as to why you can do something like
function test(node) {
node.val = 100;
}
console.log(temp.val); //prints 100
And the change in value stays; but if I make the node point to the next item in the list, that change doesn't stay.