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.