title: Creating a List Object from Array in Javascript
body: <p>I am going through Javascript from the beginning. No shortcuts, no framework, nothing. Just plain Javascript. And just for the fun of it, I am doing every exercise. Now, when I get to this one question:</p>
  
  <blockquote>
    <p>Write a function arrayToList that builds up a data structure like </p>
  </blockquote>
  
  <pre><code>var list = {
    value: 1,
    rest: {
      value: 2,
      rest: {
        value: 3,
        rest: null
      }
    }
  };
  </code></pre>
  
  <p>My code has to be able to fulfill the following:</p>
  
  <pre><code>console.log(arrayToList([10, 20])); 
  // → {value: 10, rest: {value: 20, rest: null}} &lt;== expected output which I am sure you know
  </code></pre>
  
  <p>I tried to do this recursively as the later question wants us to do it recursively (recursion is one of my weakest points!). But, I got the following code up:</p>
  
  <pre><code>var list = 
      {
        value: 0,
        rest: null
      }
  
  function arrayToList(array)
  {   
    list.value = array.shift();
  
      if(array.length!=0)
      {
        list.rest = arrayToList(array);
      }
    else
    {
      list.rest = null;
      console.log(list); //this outputs to {value: 20, rest: null}
      return list;
    } 
    return list;
  };
  </code></pre>
  
  <p>However, the output </p>
  
  <pre><code>{value: 20, rest: {value: 20, rest: {
                                        value:    20
                                        rest: {value: 20, rest: {value: 20, …}}
  }}} 
  </code></pre>
  
  <p>The ... refers to the same block of </p>
  
  <blockquote>
    <p>{value:20, rest:{value:20, rest: {...}}</p>
  </blockquote>
  
  <p>Well, I did not expand to the end to see (its too long! (after about 20 times opening is still the same) IF there is an end at all).</p>
  
  <p>Hoping to have someone guide me to the answer. I have spent couple of days on this already and am stuck.</p>
  
  <p>Thanks a lot and have a good day all!</p>