Debug my code - Find the Longest word

Where am I going wrong? Am I missing something?

My code so far:

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

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

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

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string/

Think about how the string is being broken up with your code:
var arr = str.split('');

And check out this W3schools documentation of the split() method.
https://www.w3schools.com/jsref/jsref_split.asp

A tiny change will make your code pass.

I found my mistake, and changed it…from str.split("");to str.split(" ");

My code still does not pass. I guess, I’ll be back and try some more before I ask for help.

thank you!

Sorry to hear that. I only made that little change and got your code to pass.
Hope you get it passing soon.

By the way, is your code for this exercise passing any of the tests at this point?

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

Yes willjw3, it is. Only the first test…which we have to return a number, and mine does.

Thanks @ArielLeslie…

what’s your code right now? have you done any changes?

add console.log(arr[i]) inside your loop and see what it prints and if that helps you in finding a solution

Got it everyone…I tweaked around a bit, and it passed all the tests. :+1::clap:

An alternative solution:

function findLongestWordLength(str){
    return Math.max.apply(null, str.split(' ').map((word) => word.length));
}
1 Like

@kerafyrm02, this solution would return the biggest length not the longest word.

@a-hariti: I’m going to guess you didn’t bother to click the challenge link.

Instructions: Return the length of the longest word in the provided sentence.

@kerafyrm02, my bad. An elegant solution though :+1: