Nubby question about "For loop"

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!?!?

Thanks to everybody for your answers!

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.

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…

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.


Perfect explanation!
Thank you very much for your help!