Need help with bonfire exercise


Hi everyone, wasn’t expecting to ask your help so soon again, but I’d appreciate your input.
I was breaking down the problem and by experimentation I arrived at its conclusion, which was great. The problem is I’m not understanding some of it XD.

When I arrived at the “if” statement, I was expecting to break down every element of the array that was bigger than “The”–the first element of the Array.

Below the if statement “array[i]” should be equal to the 5 biggest values in the array = quick, brown, jumped, over, lazy.

My question is shouldn’t longest = array[i] be equal to the 5 biggest? Instead of the biggest one “jumped”? At the beginning I wasn’t expecting it to return the biggest one just yet.

Can you explain to me why “longest = array[i];” automatically gave me the biggest value? Thank you.

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

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


Let me try breaking it down for you.
initially longest has the word The and when the loop begins the if statement checks if the length of the current array element is greater than the length of the value in longest variable.

i=0 3>3(false) longest="The"
i=1 5>3(true) longest="quick"
i=2 5>5(false) longest="quick"
i=3 3>5(false) longest="quick"
i=4 6>5(true) longest="jumped"
i=5 4>6 (false) longest="jumped"
i=6 3>6(false) longest="jumped"
i=7 4>6(false) longest="jumped"
i=8 3>6(false) longest="jumped"
i=9 the loop condition fails 

now longest has the string “jumped” and the return statement returns its length


Thank you sonimadhuri, you couldn’t have explained it better, I understood the process right away.