Catch Off By One Errors When Using Indexing

Tell us what’s happening:
I am supposed to subtract 1 from length to make it a 0-based index and I tried doing that in line where it says to modify by subtracting 1 from the length. It passes all tests except

“Your code should set the terminal condition of the loop so it stops at the last index.”

I don’t know what’s going on

Your code so far


function countToFive() {
  let firstFive = "12345";
  let len = firstFive.length;
  // Fix the line below
  for (let i = 0; i <= len-1; i++) {
  // Do not alter code below this line
    console.log(firstFive[i]);
  }
}

countToFive();

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing

There is a simpler way to set the condition to stop before you are out of bounds than subtracting 1.
hint

1 Like

That’s very helpful, I can’t believe I hadn’t thought of that.

soooooooo i don’t get it

For those who are searching for the right solution, here it is:

function countToFive() {
let firstFive = “12345”;
let len = firstFive.length;
// Fix the line below
for (let i = 0; i < len ; i++) {
// Do not alter code below this line
console.log(firstFive[i]);
}
}
countToFive();

All the best and have a wonderful day

1 Like

can you explain me why this code doesn’t work?

function countToFive() {
let firstFive = “12345”;
let len = firstFive.length;
// Fix the line below
for (let i = 0; i <= len-1; i++) {
// Do not alter code below this line
console.log(firstFive[i]);
}
}

countToFive();

what’s happening, what error do you get?

I was getting the same error “Your code should set the terminal condition of the loop so it stops at the last index.” if you write len -1 isnt the last index ? I didnt understand well. why i<len but not i<len-1

it behaves the same, but the tests are expecting you to use i < len

do you want to report it as a bug?

Thank you for helping make FCC better. Bugs can be reported as GitHub Issues. Whenever reporting a bug, please check first that there isn’t already an issue for it and provide as much detail as possible.

1 Like

thank you a lot! To me it seemed the same (and ıt is as you said) but I couldn’t undersand why . thank you again :slight_smile: