I do understand what happens there. But I want to visualize the whole steps.
Let me clarify:
list and head are stored across the stack with reference and pointed to the same object. okay.
when it performs list.next = { val: c, next: null}, it updates the head like { val: 0, next: { val: 1, next: null }}.
Then list = list.next happens means now the list will be { val: 1, next: null }.
Consecutively next, the head is updated to { val: 0, next: { val: 1, next: {val: 2, next: null}}}.
At this point,
- how the things happen?
- is there any reference change?
- Why head variable is indicating the last node?
let head = { val: 0, next: null };
let list = head;
const arr = [1, 2, 3, 4];
for (let c of arr) {
list.next = { val: c, next: null };
list = list.next;
}
console.log(head);
- how the things happen?
- is there any reference change?
- Why head variable is indicating the last node?

The head is not getting updated to
{ val: 0, next: { val: 1, next: null }}. The head reference never changes, and keeps referencing the same node. To makeheadpoint to a different node, you'd have to make an assignment tohead, but that never happens after the first and only assignment to it.On the other hand,
listdoes get assigned new references, which is to the last node that was created.OK. After the first two statements, where
headandlistare assigned, we have the following state:The two variables
headandlistreference the same node.In the first iteration of the loop,
cis 1, and the following property assignment is executed -- this is a mutation of the node that was created above:The effect is as follows:
The next statement is crucial: the variable
listgets a new reference. This is not a mutation, but a variable assignment:And so we get this:
Notice how
headandlistno longer reference the same node!Let's do one more iteration of the loop, with
cequal to 2. First:...leads to:
And again
list = list.next;will assign only to thelistvariable, so we get:The invariant here is that
headalways references the first node of the list, and at the start (and end) of a loop's iteration,listreferences the last node in the list.I hope this clarifies it.