1

Bit confused how this piece of code actually works, mainly because I have never seen a variable being used like this in my first language (Python)

function arrayToList(array) {
  var list = null;
  for (var i = array.length - 1; i >= 0; i--)
    list = {value: array[i], rest: list};
  return list;
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}

I am specifically confused about how list is being used with the for-loop. I understand that the first pass through, the list would look like this list = {value: array[i], rest: null};, but how is another list being nested within the first one on the second pass of the for-loop?

2 Answers 2

4

Each time the object literal is called a new object is created. The old list pointer is stored in the new list and immediately after store the pointer to the new object in the list variable.

list = null;

//First iteration
list = {value: 30, rest: null};
  │
  └────────────────────────┐
//Second iteration         │
list = {value: 20, rest: list};  //<-- see this list right here?
                                 // it's being put in before the
                                 // assignment happens.
//so this effectively becomes
list = {value: 20, rest: {value: 30, rest: null}};

//etc.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, also curious how you made that illustration?
@ApathyBear The IME I'm using let me enter box drawing characters.
1

list = {} is the same as saying list = new Object(), so you'll sometimes see Javascript code that instantiates objects on the fly like that.

These two examples represent the same object created in two different ways. They don't exactly represent your object since I create new arrays instead of show them in for loops:

//option 1
list = new Object();
list.value = new Array();
list.rest = list;

//option 1
list = {}; //new object
list.value = []; //new array
list.rest = list;

//recall these are each equivalent ways of creating the same object

Iterating through the loop, I see it's sort of a recursive construction since list uses itself as a property. The loop starts from the end of the list at 30 and works back to 10. In the first iteration rest: list refers to an object (list) that is still null as set right before the for loop begins. That's why the last value logged in the console shows null. Then reading from right to left you get 20 and then 10.

@Derek does a better job illustrating the process in his answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.