Lesson: JavaScript Algorithms and Data Structures> Debugging > Catch Off By One Errors When Using Indexing

let alphabet = "abcdefghijklmnopqrstuvwxyz";
let len = alphabet.length;
for (let i = 0; i <= len; i++) {
  console.log(alphabet[i]);
}
for (let j = 1; j < len; j++) {
  console.log(alphabet[j]);
}
for (let k = 0; k < len; k++) {
  console.log(alphabet[k]);
}

Hello guys,

I have a question about this section’s explanation (https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing) . it says says:

The first example here loops one too many times, and the second loops one too few times (missing the first index, 0). The third example is correct.

But in my console first and third case return same output: from a to z one time each letter.

Please help me understand the difference between 1 & 3 loop code outputs. Syntaxically I see difference only in <= and < but output is same.

Thank you

I think you might be overlooking the value undefined that occurs at the end of the first one. Look closely for it, it is definitely there after the z. There are 26 letters in the string so len = 26. Since arrays are indexed by 0, the last letter in the string would be alphabet[25]. But i will go to 26 in the first loop and alphabet[26] isn’t defined, thus undefined will be logged to the console on that iteration.

1 Like

Thank you. I noticed it now. However explanation of the lesson is little bit confusing:

The first example here loops one too many times, and the second loops one too few times (missing the first index, 0). The third example is correct.

Can you explain a little more about what you are confused about. I think this explanation is fairly clear. The first one loops one too many times because it uses i <= len which means it will loop when i is 26, causing the undefined value I pointed out above. The second one loops one too few times because j starts at 1 which means it won’t print out the first letter in the string since indexing starts at 0. The third loops the perfect number of times because it starts at 0 and ends at 25 which prints out the 26 letters of the alphabet.