Bug! - Find the longest word in a string

Bug! - Find the longest word in a string
0

#1

My function works, but it won’t pass me on returning 5 from “may the force be with you”.
Anyone know why? Thanks!

var largestArray = 1;

function findLongestWord(str) {
  var splitArray = str.split(" ");
  for (var i = 0; i < splitArray.length; i++) {
    if (splitArray[i].length > largestArray) {
      largestArray = splitArray[i].length;
    }
  }
  return largestArray;
}

findLongestWord("May the force be with you");

#2

Global variable, largestArray should be inside the function.

If you use global variables generally everything will break once you get to the tests:

  1. The first test will be correct
  2. Then the value of largest array will be set globally to 5
  3. Say the next test is “one two four five”: longest word has a length of 4.
  4. But the variable is already set to 5.
  5. As nothing in that set of words has a length higher than 5, it will stay as 5, and so on.

If you put it inside the function it ‘resets’ to 1 each time the function runs, which is what you want.

Also, minor, but your naming is confusing: it’s the length of the longest string/word, not the largest array


#3

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#4

Ohhh!! Ok cool, thanks for the help Dan. Yea my naming could be better for sure, I was naming stuff for myself to try to figure this task out, that’s a great reminder to recheck for readable code. This was my first forum post for help, I really appreciate it.