Syntax doubt about if keyword in Find the Longest Word in a String challenge

Hi guys, please let me understand this:
Your code so far


function findLongestWordLength(str) {
var words = str.split(" ");
var longest = "";
for (var word of words){
 if (word.length > longest.length){
longest = word; 
return longest;
 }    
}  
}

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

But if I change the syntax of the if keyword:

function findLongestWordLength(str) {
  var words = str.split(" ");
  var longest = "";
  for (var word of words){
   if (word.length > longest.length) longest = word;    
  }
  return longest;
}

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

Why happens that?
Thank you!

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0.

Challenge: Find the Longest Word in a String

Link to the challenge:

For the first one the return value of for is inside the if therefore the is likely not to work and the second one is correct.

Hi,

The second code is OK but you have to return the length of longest according to the challenge (Return the length of the longest word in the provided sentence.)

The first code has to be adjusted . As @Sajjad said the “return” is at the wrong position!

1 Like