Please explain Find the Longest Word in a String

Tell us what’s happening:
hello, i need someone to explain some part of this algorithm for me.
maxlength was initialised as zero. Now according to the If () inside the for loop. it states that if arr[i] > maxLength which is zero. it should assign arr[i].length to maxlength. i dont see any reason why this algorithm should actually return the max length because every element of arr is greater than zero. I expect this alogorithm to either return all the length of arr[i] or add them together but not print out the highest. please explain why this code does work starting from the if statement. Thanks

Your code so far


function findLongestWordLength(str) {
  var arr  = str.split(' ');
  var maxLength = 0;

  for (var i = 0; i < arr.length; i++) {
    if (arr[i].length > maxLength) {
      maxLength = arr[i].length;

  return maxLength;

var result= findLongestWordLength("The quick brown fox jumped over the lazy dog");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36.

Link to the challenge:

well, the first word has length 3, which is greater then 0, so maxLength has now value of 3, next word has length of 5, which is greater than 3, so maxLength is now 5, next word has length of 5, not bigger than 5, so maxLength stay the same, next word has length of 3, which is not bigger than 5 so […] etc

At each iteration of the loop, when that condition is true, maxLength is updated to the new value.

thank you. so we can say maxLength value is hoisted ? Thats why it is comparing the now value of maxlength instead of using the initial or global value which is zero >

it is not hoisted, it is declared before being used, not after

the value is initialized at 0, and then inside the loop it is changed if it finds something greater: you can see each iteration of the loop as being positioned below the previous one

the loop is a shortcut for this:

if (arr[0].length > maxLength) {
      maxLength = arr[0].length;
if (arr[1].length > maxLength) {
      maxLength = arr[1].length;
if (arr[2].length > maxLength) {
      maxLength = arr[2].length;
if (arr[3].length > maxLength) {
      maxLength = arr[3].length;

i think i can go with this. Thank you.