1

Beginner here. I was doing this exercise from Coding Addict.

The exercise:

function longestWords(str){
    let words = str.split(" ");
    let size = 0;
    let max = [''];

    for(let i=0; i<words.length; i++){
        if(words[i].length >= size){
            size = words[i].length;
            if(max[max.length-1].length <words[i].length){
                max = [];
                max.push(words[i]);
            }
            else{
                max = [...max,words[i]];
            }
        }
    }
    return [...max];
}

console.log(longestWords("I woke up early today"));
console.log(longestWords("I went straight to the beach"));

Now, When I tried changing the index for max[] array to i.

if(max[i].length <words[i].length){

I got this error:

Uncaught TypeError: Cannot read property 'length' of undefined at longestWords

Can someone tell me why I can't change the index and have to use max.length-1 instead?

2
  • 1
    i is used as the length of words in the loop. If i goes more than the length-1, then there won’t be an element to check. Let’s say words is 10 elements long. If you get to the second iteration of the loop and max hasn’t been added to, then you will be looking for max[1], which doesn’t exist yet. Sorry for not properly formatting, I’m on mobile. Commented Dec 16, 2020 at 2:56
  • @Rojo thankyou for the explanation! appreciate it! Commented Dec 16, 2020 at 4:32

2 Answers 2

1

When you use i, it represents the individual word in str. For example, "I woke up early today" has 5 words( or length = 5 ), but your max array has only 1 in length (which is ''). So if you use i to access max array you will get index out of bound. Unless you use the str has the same length as max.

Sign up to request clarification or add additional context in comments.

2 Comments

ah yes, understood. I can totally see that! thank you so much!
@NickParsons ohh I see, okay, I just marked it. thanks for pointing that out!
0

because your max array has always one element so there is no entry in the index 1 which is max[max.length], so you better actually write it as max[0] instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.