Iterators in JavaScript and remembering position This is an attempt to write a function link that creates a linked list from an array:



function link(list) {
    let next = tail = null;

    for(let i = list.length-1; i &gt;= 0; i--) {        
      const value = list[i];        
      next = { value, next };
    }

    let cursor = head = next;

    function* iterator() {
      while(cursor.next) {
        yield cursor;
        cursor = cursor.next
      }
      yield cursor;
    }

    return {
      [Symbol.iterator]: iterator,
      head,
      tail,
    };
}

console.log(...link([1,2,3,4]));




The iterator maintains a cursor to remember its position in the iteration. 

This feels wrong and brittle. 

Is it? 

If so, how should the iterator be implemented here.
How about the following recursive approach



function link(list) {
    if(!list.length)
        return [];

    let [car, ...cdr] = list;
    return {
        car,
        cdr: link(cdr),
        [Symbol.iterator]: function*() {
            yield this;
            yield *this.cdr;
        }
    }
}

ls = link([1, 2, 3, 4])

for (let t of ls)
    console.log(t.car)