Understanding a recursive function

Understanding a recursive function
0.0 0

#1

The example I’m having trouble understanding is from the book Javascript Allonge (https://leanpub.com/javascriptallongesix/read).

It takes a linked list and makes a copy of it.

const EMPTY = {};
const OneToFive = { first: 1, 
                    rest: {
                      first: 2,
                      rest: {
                        first: 3,
                        rest: {
                          first: 4,
                          rest: {
                            first: 5,
                            rest: EMPTY } } } } };

const copy = (node, head = null, tail = null) => {
  if (node === EMPTY) {
    console.log(head)
    return head;
  }
  else if (tail === null) {
    const { first, rest } = node;
    const newNode = { first, rest };
    return copy(rest, newNode, newNode);
  }
  else {
    const { first, rest } = node;
    const newNode = { first, rest };
    tail.rest = newNode;
    return copy(node.rest, head, newNode);
  }
}
copy(OneToFive);

In particular, what I don’t understand is how it winds up. Why does tail.rest = newNode affect the final thing that gets returned? I think the final thing that gets returned is head in the node === EMPTY case but it seems as if throughout the function, nothing is actually modifying head…so it can’t be that?

Please help me out!


#2

I think I figured it out after sleeping.
head doesn’t need to be altered because at the tail === null section, an entirely new object is assigned the value head. The tail of this new head still points to the old tail, though, and so on the next pass through (in the else clause) tail.rest gets pointed to the new object.