I am looking at this exercise from the book Eloquent Javascript, Chapter 4 - A List for quite some time and I\'m trying to understand how this particular function works:
I've tried to explain a little here. Let me know if something is unclear
function arrayToList(array) {
// declare a empty variable to use is as a list
let list = null;
// Now iterate from the last element to the first. Example [10, 20]
for (let i = array.length - 1; i >= 0; i--) {
// iteration 1: i = 1
// we assign to list...
list = {
//the value of the current element
value: array[i], // value = 20
// the current list value before current assign
rest: list // rest = null
};
// now it is assigned. list = {value: 20, rest: null}
// ....
// iteration 2: i = 0
// we assign to list...
list = {
//the value of the current element
value: array[i], // value = 10
// the current list value before current assign
rest: list // rest = {value: 20, rest: null}
};
// now it is assigned. list = {value: 10, rest: {value: 20, rest: null}}
}
return list;
}