Why does this not work? (Longest word algorithm)

Why does this not work? (Longest word algorithm)
0.0 0

function findLongestWord(str) {
  var arr = str.split(" ");
  var len;
    var x = arr[i].length;
    var y = arr[i+1].length;  //js casts these into strings when using for loops
    if (y > x){
      len =  Number(y.length);
    else continue;
  return len;

findLongestWord("The quick brown fox jumped over the lazy dog");


In C++ something like this would work… why does it not work in js? Seems consistent with all of the syntax that I’ve read so far, what am I missing?


Your problems are with logic instead of syntax.

  • You are comparing the wrong values.
  • You are potentially hitting an array out of bounds error (depending on your input).
  • You are returning at the wrong time.

Some other things:

  • Array.length returns a number. You don’t need to cast it.
  • There is no reason to use continue


I Really appreciate your timely response to my question!!

The error I am getting in console is this, but I was still getting this error after casting it… this is just one of many iterations coming at this problem and I figured I’d ask for help.

You state that I am comparing the wrong values, am I not comparing the length of the strings at the given indices of the array?

I understand what you mean by the out of bounds error and the unnecessary usage of the continue keyword.

Uncaught TypeError: Cannot read property ‘length’ of undefined
at findLongestWord (:10:22)
at :22:1


Why are you comparing neighboring values? What if the very first item in your array is the longest word?

The error “Cannot read property length of undefined” is due to your index out of bounds. The last arr[i+1] doesn’t exist because you are looping to the end of the array. In JavaScript that means that arr[i+1] is undefined and you can’t get its length.


Hi cafeTechne!

Awesome work so far. Your error is being caused by the out-of-bounds issue. Let’s say that you get an array ["a", "b", "c"]. Then, in the for loop, x and y take on the following values

i       x             y
0     arr[0]       arr[1]
1     arr[1]       arr[2]
2     arr[2]       arr[3]

But wait! arr[3] doesn’t exist! You can fix this by getting rid of the final iteration (i.e., never setting i to 2). That’ll mean you’ll need to change the condition you use in your for loop.

The second issue is that you’re comparing the wrong values (as said by @ArieLeslie). Consider the following array

["Verylongword", "Tiny", "Medium"]

What we want to find is the length of the first word in there, because it’s the longest. But let’s pretend to be the computer and see what happens on each iteration (like we did last time). In the below, I’ve imagined that we’ve fixed the other bug, so the last iteration won’t happen.

i            x.length             y.length         comparison             len
0               12                      4            4 > 12            undefined
1                4                       6            6 > 4                6                 

What should’ve happened is:

  • len gets set to 12
  • len doesn’t change

But instead it goes in the wrong order, and in fact sets len to 6, which isn’t what we want!

It’s comparing each value to the one before it, but, as you saw in this example, just because it’s not the shortest doesn’t mean it’s the longest. Your code will pick the last word that had a shorter word directly before it, and return its length. I suggest you compare each word with the best candidate so far, so as not to override a better candidate that came earlier.

//js casts these into strings when using for loops

I promise you it doesn’t! For proof, feel free to add

console.log(typeof x);

and you’ll see an output of number. :slight_smile:

I wish you the best of luck – you’ve got some excellent code so far.


Thank you so much! This is really the BEST explanation to a problem I have ever seen–I am absolutely serious! The way you set up the variables into a grid made it so much easier for me to think through the problem and the attention to detail you offered in your narratives were wonderful.

I see exactly what I was doing wrong now. Thank you so very much! ::high five::


After reading your response, I decided to retire for the evening. I just woke up and it took me less than a minute to incorporate the above guidance. What follows is my solution!

function findLongestWord(str) {
  var arr = str.split(" ");
  var len = 0;
    var x = arr[i].length;
    if (x > len){
      len =  x;
    else continue;
  return len;

findLongestWord("The quick brown fox jumped over the lazy dog");

Thank you very much once again! @ArielLeslie and @joker314 !