Stack at fcc javascript challenge

Hello this is a fcc javascript alg. challenge and the code is supposed to find the longest word in a string but I dont understand this block of code which turns out to be the answer


function findLongestWordLength(str) {
  let record = 0;
  let i = 0;
  let wordLength = 0;
  while(true) {
    wordLength = str.indexOf(' ', i) - (i);
    if (str.indexOf(' ', i) === -1) {
      wordLength = str.length-i;
    }
    i = i + (wordLength > 0 ? wordLength : wordLength*(-1)) + 1;
    // OR...
    // i += Math.abs(wordLength)+1;
    if (wordLength > record) {
      record = wordLength;
    }
    if (i > str.length) {
      break;
    }
  }
  return record;
}

can anyone help me out

const str = "Tony Montana Scarface"

indexOf(char, startIndex)
This will look for the given character in a string starting from the given startIndex.
If it finds any, returns its index position corresponding to that character inside the string.

str.length = 21
First time while loop,

  • i = 0

  • for the first time indexOf finds white space position at 4

wordLength = str.indexOf(' ', 0 ) - 0 => 4 - 0 = 4 //Tony

It will ignore if statement, since it found white space.

wordLength is bigger than 0 , result will be 4.

(wordLength > 0 ? wordLength : wordLength*(-1))
  • i will be = 4 + 1 = 5

  • record = wordLength = 4

**End of first loop
**Starts loop for the second time

  • i = 5
    Its gonna start looking for white spaces from index position 5.
    It will find white space position at 12.

  • wordLength = 12 - 5 = 7 // Montana
    Not gonna enter if statement, since it found one.

 wordLenght > 0
 so i will be = 5 + 7 + 1 = 13

// this time record = 4, wordLenght = 7
// so new record will be = 7;
if (wordLength > record) {
      record = wordLength;
    }
* i = 13
* record = 7

**End of second loop
**Starting the loop for the third time

This time it will not find any white space
It will go into if statement.

  • `wordLenght = 21 - 13 = 8 //Scarface
  • i will be = 13 + 8 + 1 = 22

new record will be changed since this time wordLenght 8 bigger than 7

  • record = 8
  • i = 22
// 22 > 21 it will break the loop,
 if (i > str.length) {
      break;
    }

//end of loop

1 Like

No wonder why this code confuses you… it frankly confuses me too :slight_smile:
Whenever you see black magic lines like while(true) it might be not worth to research and study such algorithm. If you need something to research, you can try this solution:

const findLongestWordLength = (str) => str.match(/\b\w+/g).reduce((max, word) => word.length > max ? word.length : max, 0);
1 Like

Since you are a developer i hope you understand
my problem is

let theSyntax = indexOf();

In the lessons I learnt that &{theSyntax} returns the index of an element in a given array ,
but in this code &{theSyntax} is performing another function and is accepting " as an argument