0
let ob = {
    head:{next:0}, 
    tail:2
}

let first = ob.head; //{next:0}
ob.tail = ob.head; // {next:0}
let second = ob.head.next // 0
first.next =2

console.log(ob.tail === first). //true
console.log(first.next === second) //false
console.log("first= " + JSON.stringify(first)) //first= {"next":2}
console.log("second= " + JSON.stringify(second)) //second= 0
console.log("ob.tail= " + JSON.stringify(ob.tail)) //ob.tail= {"next":2}
console.log("ob.head= " + JSON.stringify(ob.head)) //ob.head= {"next":2}
console.log(ob)

In these codes, I am so confused that why when the first.next = 2 doesn't change the variable second?

Can anyone help to explain it?

I changed the origianl next to object2 the new code is like this

let ob = {
    head:{next:{test:9}}, 
    tail:2
}

let first = ob.head; 
ob.tail = ob.head; 
let second = ob.head.next 
console.log(first.next === second) //true
first.next ={test:0}

console.log(ob.tail === first) //true
console.log(first.next === second) //false
console.log("first= " + JSON.stringify(first)) //first= {"next":{"test":0}}
console.log("second= " + JSON.stringify(second)) //second= {"test":9}
console.log("ob.tail= " + JSON.stringify(ob.tail)) //ob.tail= {"next":{"test":0}}
console.log("ob.head= " + JSON.stringify(ob.head)) //ob.head= {"next":{"test":0}}
console.log(ob)


As showing the second before the second change is the same as first.next but it doesn't change simultaneously. Why is that?

s c
  • 21
  • 3
  • Because not *variables* are linked by references, but *values* are. `second` holds the value `2`. There is no way to change the value of `2`. `2` will always be `2`. But `first` holds an *object*, and changing a property of that object still means it's the same object, just mutated. – deceze Dec 04 '22 at 09:03
  • You can visualize your code at http://pythontutor.com, which will probably help… – deceze Dec 04 '22 at 09:30
  • Ok, it seems a wonderful tool to learn coding, thank you, deceze. – s c Dec 04 '22 at 09:41

0 Answers0