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:
TL;DR: In each iteration, we create a new object containing the object from last iteration.
In the line list = {value: array[i], rest: list};
, the statement on the right of the =
gets evaluated first. This means we create an object {value: array[i], rest: list}
, containing the current values of array[i]
and list
. In the first iteration, list
is null
and array[i]
is 20, so the object looks like this:
{value: 20, rest: null}
Only then do we assign this object to list
.
In the next iteration, list
isn’t null
anymore, but {value: 20, rest: null}
. So now, the object we create and assign to list
looks like this:
{value: 10, rest: {value: 20, rest: null}}