Find the Longest Word in a String. Why

cod is `var rememberLength = 0;

function findLongestWord(items) {
var item = items.split(’ ');
for (var index = 0; index < item.length; index++) {
var element = item[index].length;
wynik = chcekLength(element);
}

return wynik;
}
function chcekLength(element) {
if (rememberLength < element) {
rememberLength = element;

}
return rememberLength;

}
findLongestWord(“May the force be with you”);
This code return 5 but dont pass test in this string example.

Stumped me for a minute, then I realized you declared remberLength (first line) as a global variable.

The first test is

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

which returns 6. Because your chcekLength function assigns a value to rememberLength, the value 6 is still assigned to it when the next test runs. Since your if statement in chcekLength checks to see if rememberLength is less than element, it will not get set to 5, because 6 > 5.

If you modify your existing chcekLength function as follows, you will see what is the value of rememberLength is before and after the if statement in chcekLength:

function chcekLength(element) {
  console.log('inside chcekLength before if rememberLength='+rememberLength);
  if (rememberLength < element) {
    rememberLength = element;
  }
  console.log('inside chcekLength after if rememberLength='+rememberLength);
  return rememberLength;
}

This is a great example of how global variables can cause unexpected results. See if you can modify your code to not use a global variable. I have a few suggestions you can make without making a lot of changes to your existing code:

  1. Declare your local variable wynik inside your findLongestWord function and set it equal to zero. This will make sure when ever a new test sentence is sent to the function, the longest word length will start of at zero each time (something your global rememberLength variable did not do).

  2. Add a 2nd argument to your chcekLength function and call it rememberLength. Where you call the function chcekLength, make sure you add a 2nd parameter (in your code, that would be wynik. This will send both wynik (which holds the largest number so far in the sentence) and the current element length to the chcekLength function and then it will make the comparison and send back the larger of the two and assign it to wynik.

  3. Two extra recommendations are:

  • Change the name of your chcekLength function to checkLength

  • Rename your wynik variable to something the indicates what is being held in it, such as largest to make it easier to read.

Thanks a lot. I will check this tomorrow how it will be work. I will change my code and i’m going to write new version of it.