1

I'm brand new to coding, have only been doing it for about two weeks. I'm doing freecodecamp and i'm having trouble understanding why my code isn't working. The goal is to make a function that receives a string and then finds the longest word and gives you the amount of characters in the word. I would appreciate any advice.


function findLongestWordLength(str) {
  
  let string = /\w+/g;
  let arrayString = str.match(string);
  let wordCount = arrayString[0].length; 

  for (let n= 1; n > arrayString.lentgh; n++){
      if (wordCount < arrayString[n].length){
          return wordCount = arrayString[n].length;
      }
  } 
  return wordCount;

}

console.log(findLongestWordLength("Thep quick brown fox jumped over the lazy dog"));

3 Answers3

0

There are few mistakes & typos in your code.

  1. Inside for your condition should be n < arrayString.length;.
  2. Do not use return from if block.
  3. There is typo in your for condition. You used arrayString.lentgh it should be length.

Try it below.

function findLongestWordLength(str) {
  
  let string = /\w+/g;
  let arrayString = str.match(string);
  let wordCount = arrayString[0].length; 

  for (let n= 1; n < arrayString.length; n++){
      if (wordCount < arrayString[n].length){
          wordCount = arrayString[n].length;
      }
  } 
  return wordCount;

}

console.log(findLongestWordLength("Thep quick brown fox jumped over the lazy dog"));

P.S. You can debug code in browser console as well.

For reference :

Karan
  • 12,059
  • 3
  • 24
  • 40
0

The error is in this part:
Your second statement of the for loop is inccorect.
The second statement should be the condition that the loop stops, Here, your n = 1, but arrayString.length is already 9 (because the array has 9 words).
So, the for loop never runs, ending up returning the wordCount of the first word (arrayString[0]) (also check for spelling errors)

Secondly, don't use return in the loop because it will "return" out of the function, exiting it before it finishes running.
Instead, simply reassign the wordCount.

for (let n= 1; n > arrayString.lentgh; n++){
//            ^^^^^^^^^^^^^^^^^^^^^^^^
      if (wordCount < arrayString[n].length){
          return wordCount = arrayString[n].length;
//        ^^^^^^
      }
  } 

Changed:

for (let n= 1; n < arrayString.length; n++){
      if (wordCount < arrayString[n].length){
          wordCount = arrayString[n].length;
      }
  } 
science fun
  • 401
  • 4
  • 8
0

Though, below is not the answer, but is another solution.

function findLongestWordLength(str) {
 
 const splitted = str.split(' ');
 let wordLength =0;
 splitted.forEach((word) =>{
     const wordSplitted = word.split('');
     if(wordSplitted.length > wordLength){
      wordLength = wordSplitted.length;
     }
 });

  return wordLength;

}

console.log(findLongestWordLength("Thep quick brown fox jumped over the lazy dog"));
Alaksandar Jesus Gene
  • 6,523
  • 12
  • 52
  • 83