I'm working on getting started with JavaScript. I implemented a simple function to convert an array to a singly linked list, and then iterate over it recursively to return the value at a particular position. My code currently logs undefined for all position values except 0. What causes it to behave this way?
var list = arrayToList([1,2,3,4,5]);
function arrayToList(arr) {
var list = null;
for (var i = arr.length - 1; i >= 0; i--) {
list = {value : arr[i], rest: list};
}
return list;
}
function nth(list, count) {
if (!list) return undefined;
if (count == 0) return list.value;
else nth(list.rest, count - 1);
}
console.log(nth(list,2));