Nubby question about "For loop"

Nubby question about "For loop"
0

#1

Sorry for my dummy question, but I can’t understand why we should use other variable (longestWord)
in this example:

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

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

and what is the logic? if longest word is smaller than length of my array, so make longest word equal to array element!?!?
WTF??

Thanks to everybody for your answers!


#2

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 if statement:

  if (longestWord < array[i].length)
    {
      longestWord = array[i].length;
    }

is asking if the length of the current array element (a word) is less than longestWord (which contains the value of the longest word length seen so far), then assign the current word’s length to longestWord.


#3

Where var “longestWord” contain the value of the max num?
longestWord = 0
and after all we assign the value of array[i].length to this variable, but it doesn’t mean that it’s the longest value…


#4

I added console.log statements to the original code you posted, so you could see what is happening with the longestWord variable. Click the Run (right arrow) in the code below to run the code.


#5

Perfect explanation!
Thank you very much for your help!