JavaScript LinkedList removeHead() could be better

In your Comparing Rust and JavaScript Ergonomics with a Simple Linked List article, you give the following JavaScript function:

LinkedList.prototype.removeHead = function() {
  const currentHead = this.head;
  const newHead = this.head.next;
  if (newHead === null) {
    this.tail = null;
  }
  this.head = newHead;
  return currentHead ? currentHead.value : null;
};

You mention that:

Finally, we're getting somewhere where the Rust and JavaScript implementations don't look like straight copy-paste jobs.

But I was struck by the fact that the above function is not doing the same thing as its Rust counterpart:

pub fn remove_head(&mut self) -> Option<i32> {
    if let Some(head) = &mut self.head {
	let old_value = Some(head.value);
	let new_head = head.next.take();
	if new_head.is_none() {
	    self.tail = None;
	};
	self.head = new_head;
	old_value
    } else {
	None
    }
}

Note that the Rust function is first checking self.head, but, in line 3 of the JavaScript implementation, you try this.head.next without first checking if this.head is null. The consequence of this is (in a JavaScript console):

> const list = new LinkedList();
> list.removeHead();
/*
Uncaught TypeError: Cannot read property 'next' of null
    at LinkedList.removeHead (<anonymous>:3:29)
    at <anonymous>:1:6
*/

I believe a better JavaScript implementation would be:

LinkedList.prototype.removeHead = function() {
  if (this.head) {
    const oldValue = this.head.value;
    const newHead = this.head.next;
    if (newHead === null) {
      this.tail = null;
    }
    this.head = newHead;
    return oldValue;
  } else {
    return null;
  }
};

This more closely resembles the Rust function and does not have the potential bug caused by calling removeHead() on an empty list.

Following the conclusion style of your article, I think the lesson to be learned here is that, in addition to Rust being pretty and unsafe not being scary, Rust, by its nature, makes it harder to introduce bugs than JavaScript.

Edited by Sean Leather