Search code examples
javascriptloopsiteratorjavascript-engine

Understanding how the JS engine is looping through to get the index of an array element


I wrote a function to output the names and real-life indexes of people waiting in a line.

var line = ["Sarah", "Mike", "Bob"];

function currentLine(line) {
  if (line.length === 0) {
    document.write(`The line is currently empty.`);
  } else {

    var array = [];
    for (var i = 0; i < line.length; i++) {
      array.push(` ${line.indexOf(line[i+1])}. ${line[i]}`);
    }
    document.write(`The line is currently:` + array);
  }
}

currentLine(line);

When I run the function, the output is:

The line is currently: 1. Sarah, 2. Mike, -1. Bob

How is the JavaScript engine interpreting the loop? How is Bob -1? Last time I checked 2 + 1 = 3.

I want to fix this myself but I'm trying to understand what is going on in this seemingly straight forward loop.


Solution

  • The answer is right in your analysis:

    How is Bob -1? Last time I checked 2 + 1 = 3

    On the third iteration of the loop, i = 2. This line executes with i = 2:

    line.indexOf(line[i+1])
    

    So what does this say? It says get me the element at position (i + 1), which is position 3, or the forth element. There is no forth element, so line[i+1] is undefined.

    Pass that to the indexOf call and what you are saying is, find me the position of undefined in the line array. line contains 'Sarah', 'Mike', and 'Bob'. It does not contain undefined.

    I made a small change to the array.push line and it works correctly now:

    var line = ["Sarah", "Mike", "Bob"];
    
    function currentLine(line) {
      if (line.length === 0) {
        document.write(`The line is currently empty.`);
      } else {
    
        var array = [];
        for (var i = 0; i < line.length; i++) {
          array.push(` ${i+1}. ${line[i]}`);
        }
        document.write(`The line is currently:` + array);
      }
    }
    
    currentLine(line);