Skip to content
Advertisement

Linked List how to add value to from an array?

I am following a linked list problem in Eloquent JavaScript book and I don’t understand how the value for the first link is 10 and not 20 if i is = 1, in the first iteration of the for loop.

function arrayToList(array) {
  let list = null;
  for (let i = array.length - 1; i >= 0; i--) {
    list = { value: array[i], rest: list }; //why is the value 10 and not 20 if i = 1, 
  }
  return list;
}
console.log(arrayToList([10, 20]));

{value: 10, rest: {value: 20, rest: null}}

I think I am thinking of the for loop the wrong way, but I don’t know where.

Advertisement

Answer

The value is 20. The explanation is that the loop is running backwards, adding list as a value of the property rest. Thus, the outermost object has the first value in the array and the innermost object has the last value in the array.

Have a look at this demo, where the console shows the values for each iteration:

function arrayToList(array) {
  let list = null;
  for (let i = array.length - 1; i >= 0; i--) {
    console.log(`The index is ${i} and the value is ${array[i]}`)
    list = { value: array[i], rest: list }; //why is the value 10 and not 20 if i = 1, 
  }
  return list;
}
arrayToList([10, 20]);
Advertisement