0

First question on Stack Overflow, couldn't find an answer elsewhere.

In this exercise I'm sorting an array. Names with four characters get to be in their own array. It seemed simple enough:

    let trueFriends = [];
function friendSorter(friends) {
    //your code here
    for (let i = 0; i <= friends.length; i++) {
        if (friends[i].length === 4) {
            console.log(`${friends[i]} is a friend of mine`);
            trueFriends.push(friends[i]);
        } else {
            console.log(`${friends[i]} is a sworn enemy!`);
        }
    }
    console.log(trueFriends);
}
friendSorter(["Jimm", "Cari", "aret", "truehdnviegkwgvke", "sixtyiscooooool"]);

But at friends[i].length === 4 i get an error that it cannot read the length of undefined. What makes it odder to me is if I log friends[i].length (or just friends[i]) it gives me each items length or name. What's more from the console I can access trueFriends and the names have been filtered into there as expected.

So I guess my question is why am I getting an error if things seem to still be working.

Thank you for your help!

  • 6
    `i <= friends.length` should be `i < friends.length`, otherwise it will loop one too many times. – Ivar Jun 27 '21 at 15:09
  • "things seem to still be working" is because the error happens after all the elements in the friends array have been processed. The error happens when i == friends.length which is one index position beyond the last element in friends. – Charlie Wallace Jun 27 '21 at 15:11

0 Answers0